Skip to content

Commit

Permalink
Merge pull request pyrus#2 from till/master
Browse files Browse the repository at this point in the history
Related to pyrus#1
  • Loading branch information
saltybeagle committed Jul 12, 2011
2 parents 42dea60 + 2154f70 commit e8d9d27
Show file tree
Hide file tree
Showing 15 changed files with 172 additions and 52 deletions.
2 changes: 1 addition & 1 deletion .gitignore
@@ -1 +1 @@
/config.inc.php
config.inc.php
26 changes: 21 additions & 5 deletions README → README.md
Expand Up @@ -18,18 +18,34 @@ I just used what I knew... so it's a mysql db using the mysqi ext and a stupid a

Clone the repo!

There's a Config class with the default configuration in it.
There's a Config class in `etc/` with the default configuration in it.
Just copy it to `config.inc.php` and adjust paths.

You'll need a checkout of PEAR2_Pyrus as well: https://github.com/pyrus/Pyrus

Create a DB that can be connected using `mysqli://pearhunt:pearhunt@localhost/pearhunt`
run `php upgrade.php` from cli to setup the DB
run `php scripts/addChannel.php pear.php.net` to add a channel to the db

If you want to use your own mysql credentials, copy `etc/config.sample.php` to `config.inc.php` and add the following:

Config:setDbSettings(array(
'host' => 'example.org',
'username' => 'mysql user',
'password' => 'super secret password'
'dbname' => 'my_database',
));

Finally:

run `./scripts/upgrade.php` from cli to create and setup the DB
run `./scripts/addChannel.php pear.php.net` to add a channel to the db.

=== Indexing PEAR channels ===

Add a channel and discover all packages:
`php scripts/addChannel.php pear.example.com`
`./scripts/addChannel.php pear.example.com`

Update a channel:
`php scripts/updateChannel.php pear.example.com`
`./scripts/updateChannel.php pear.example.com`

=== Searching! ===

Expand Down
6 changes: 6 additions & 0 deletions bootstrap.php
@@ -0,0 +1,6 @@
<?php
if (file_exists(__DIR__ . '/etc/config.inc.php')) {
require_once __DIR__ . '/etc/config.inc.php';
} else {
require_once __DIR__ . '/etc/config.sample.php';
}
1 change: 1 addition & 0 deletions data/pearhunt.sql
Expand Up @@ -29,6 +29,7 @@ CREATE TABLE IF NOT EXISTS `channels` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`alias` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`description` mediumtext COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 ;
Expand Down
2 changes: 1 addition & 1 deletion config.sample.php → etc/config.sample.php
Expand Up @@ -14,7 +14,7 @@ function autoload($class)

spl_autoload_register("autoload");

set_include_path(__DIR__ . '/src');
set_include_path(__DIR__ . '/../src');


$config = \PEAR2\Pyrus\Config::singleton('/tmp');
Expand Down
18 changes: 18 additions & 0 deletions etc/nginx-pearhunt.conf
@@ -0,0 +1,18 @@
server {
listen PORT_HERE;
server_name SERVER.NAME.HERE;

root PATH/TO/pearhunt/www;
index index.php;

try_files $uri @php_upstream;

location @php_upstream {
include fastcgi_params;

fastcgi_pass unix:/tmp/.fastcgi.till/socket;
fastcgi_index index.php;

fastcgi_param SCRIPT_FILENAME PATH/TO/pearhunt/www$fastcgi_script_name;
}
}
16 changes: 6 additions & 10 deletions scripts/addChannel.php 100644 → 100755
@@ -1,26 +1,22 @@
#!/usr/bin/env php
<?php
if (file_exists(dirname(__FILE__).'/../config.inc.php')) {
require_once dirname(__FILE__).'/../config.inc.php';
} else {
require_once dirname(__FILE__).'/../config.sample.php';
}
require_once __DIR__ . '/../bootstrap.php';

if (!isset($_SERVER['argv'], $_SERVER['argv'][1])
|| $_SERVER['argv'][1] == '--help' || $_SERVER['argc'] != 2) {
echo "This program requires 1 argument.\n";
echo "addChannel.php channel\n\n";
echo "Example: addChannel.php pear.php.net\n";
echo "This program requires 1 argument." . PHP_EOL;
echo "addChannel.php channel" . PHP_EOL . PHP_EOL;
echo "Example: addChannel.php pear.php.net" . PHP_EOL;
exit(1);
}

if ($channel = Channel::getByName($_SERVER['argv'][1])) {
echo "That channel already exists!\n";
echo "That channel already exists!" . PHP_EOL;
} else {
$channel = new \Channel();
}

echo "Adding channel...\n";
echo "Adding channel..." . PHP_EOL;


$pyrus_channel = new Remote_PyrusChannel($_SERVER['argv'][1]);
Expand Down
6 changes: 1 addition & 5 deletions scripts/updateChannel.php 100644 → 100755
@@ -1,10 +1,6 @@
#!/usr/bin/env php
<?php
if (file_exists(dirname(__FILE__).'/../config.inc.php')) {
require_once dirname(__FILE__).'/../config.inc.php';
} else {
require_once dirname(__FILE__).'/../config.sample.php';
}
require_once __DIR__ . '/../bootstrap.php';

if (!isset($_SERVER['argv'], $_SERVER['argv'][1])
|| $_SERVER['argv'][1] == '--help' || $_SERVER['argc'] != 2) {
Expand Down
15 changes: 8 additions & 7 deletions upgrade.php → scripts/upgrade.php 100644 → 100755
@@ -1,13 +1,14 @@
#!/usr/bin/env php
<?php
if (file_exists(__DIR__ . '/config.inc.php')) {
require_once __DIR__ . '/config.inc.php';
} else {
require __DIR__ . '/config.sample.php';
}
require_once __DIR__ . '/../bootstrap.php';

// create the database (if necessary)
Database::create();

echo 'Connecting to the database&hellip;'.PHP_EOL;
$db = Record::getDB();
echo 'connected successfully!<br />'.PHP_EOL;

/**
*
* Enter description here ...
Expand All @@ -22,11 +23,11 @@ function exec_sql($db, $sql, $message, $fail_ok = false)
$result = $db->multi_query($sql);
if (!$result) {
echo 'The query failed: ';
echo $mysqli->error;
echo $db->error;
exit(1);
}
echo 'finished.<br />'.PHP_EOL;
}
exec_sql($db, file_get_contents(__DIR__ . '/data/pearhunt.sql'), 'Initializing database structure');
exec_sql($db, file_get_contents(__DIR__ . '/../data/pearhunt.sql'), 'Initializing database structure');

echo 'Upgrade complete!';
51 changes: 51 additions & 0 deletions src/Database.php
@@ -0,0 +1,51 @@
<?php
/**
* Simple Active Record implementation for pearhunt
*
* PHP version 5
*
* @category Utilities
* @package pearhunt
* @author Till Klampaeckel <till@php.net>
* @copyright 2011 Till Klampaeckel
* @license http://www1.unl.edu/wdn/wiki/Software_License BSD License
* @link http://pear2.php.net/
*/

/**
* Simple active record implementation for pearhunt.
*
* PHP version 5
*
* @category Utilities
* @package pearhunt
* @author Till Klampaeckel <till@php.net>
* @copyright 2011 Till Klampaeckel
* @license http://www1.unl.edu/wdn/wiki/Software_License BSD License
* @link http://pear2.php.net/
*/
class Database
{
/**
* Create the database.
*
* @return void
* @throws RuntimeException When it didn't work.
*
* @uses Config::getDbSettings()
* @uses Record::getDb()
*/
public static function create()
{
$settings = Config::getDbSettings();
$db = Record::getDb(false);

$dbName = $db->real_escape_string($settings['dbname']);

$sql = "CREATE DATABASE IF NOT EXISTS $dbName";
if ($db->query($sql) === true) {
return;
}
throw new RuntimeException($db->error, $db->errno);
}
}
8 changes: 6 additions & 2 deletions src/Package.php
Expand Up @@ -14,7 +14,11 @@ public function getTable()
public static function getByChannelAndName($channel, $name)
{
$mysqli = self::getDB();
$sql = 'SELECT * FROM packages WHERE channel_id = '.(int)$channel->id.' AND name = "'.$mysqli->escape_string($name).'";';

$sql = 'SELECT * FROM packages WHERE channel_id = ';
$sql .= (int)$channel->id;
$sql .= ' AND name = "' . $mysqli->escape_string($name) . '";';

if (($result = $mysqli->query($sql))
&& $result->num_rows > 0) {
$object = new self();
Expand All @@ -23,4 +27,4 @@ public static function getByChannelAndName($channel, $name)
}
return false;
}
}
}
24 changes: 20 additions & 4 deletions src/PackageSearch.php
Expand Up @@ -7,12 +7,28 @@ class PackageSearch extends Packages
function __construct($options)
{
$this->options = $options + $this->options;
$records = array();
$mysqli = Record::getDB();

$sql = 'SELECT packages.* FROM packages';

if (isset($options['q']) && !empty($options['q'])) {
$sql .= ' WHERE name LIKE "%';
$sql .= $mysqli->escape_string($options['q']);
$sql .= '%" OR description LIKE "%';
$sql .= $mysqli->escape_string($options['q']);
$sql .= '%"';
}

$records = array();
$mysqli = Record::getDB();
$sql = 'SELECT packages.* FROM packages WHERE name LIKE "%'.$mysqli->escape_string($options['q']).'%" OR description LIKE "%'.$mysqli->escape_string($options['q']).'%"';
if ($result = $mysqli->query($sql)) {
$records = $result->fetch_all(MYSQL_ASSOC);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$records[] = $row;
}
$result->free();
}
}
parent::__construct(new ArrayIterator($records), $this->options['offset'], $this->options['limit']);
}
}
}
33 changes: 25 additions & 8 deletions src/Record.php
Expand Up @@ -158,9 +158,11 @@ function update()
protected function prepareAndExecute($sql, $values)
{
$mysqli = self::getDB();

if (!$stmt = $mysqli->prepare($sql)) {
throw new Exception('Error preparing database statement! '.$mysqli->error, 500);
throw new RuntimeException(
"Error preparing database statement! ($sql): $mysqli->error",
500
);
}

call_user_func_array(array($stmt, 'bind_param'), $values);
Expand Down Expand Up @@ -327,19 +329,34 @@ public static function getByAnyField($class, $field, $value, $whereAdd = '')
/**
* Connect to the database and return it
*
* @param boolean $useDb To use the db in the connection, or not.
*
* @return mysqli
*/
public static function getDB()
public static function getDB($useDb = true)
{
if (!is_bool($useDb)) {
throw InvalidArgumentException("Must be boolean.");
}
static $db = false;
if (!$db) {
static $settings;

if ($settings === null) {
$settings = Config::getDbSettings();
$db = new mysqli($settings['host'], $settings['user'], $settings['password'], $settings['dbname']);
}

if (!$db) {
if ($useDb === true) {
$db = new mysqli($settings['host'], $settings['user'], $settings['password'], $settings['dbname']);
} else {
$db = new mysqli($settings['host'], $settings['user'], $settings['password']);
}
if ($db->connect_error) {
die('Connect Error (' . $db->connect_errno . ') '
. $db->connect_error);
throw new RuntimeException('Connect Error (' . $db->connect_error . ')', $db->connect_errno);
}
$db->set_charset('utf8');
} else {
$db->select_db($settings['dbname']);
}
return $db;
}
Expand Down Expand Up @@ -380,4 +397,4 @@ function toArray()
{
return get_object_vars($this);
}
}
}
8 changes: 2 additions & 6 deletions www/index.php
@@ -1,9 +1,5 @@
<?php
if (file_exists(dirname(__DIR__).'/config.inc.php')) {
require_once dirname(__DIR__).'/config.inc.php';
} else {
require_once dirname(__DIR__).'/config.sample.php';
}
require_once __DIR__ . '/../bootstrap.php';

$request = new Request($_GET, $_POST, $_FILES);

Expand All @@ -23,4 +19,4 @@

$savvy->addGlobal('controller', $controller);
$savvy->addGlobal('request', $request);
echo $savvy->render($controller);
echo $savvy->render($controller);
8 changes: 5 additions & 3 deletions www/templates/json/PackageSearch.tpl.php
@@ -1,4 +1,6 @@
<?php
foreach ($context as $package) {
echo '"'.$package->name.'":'.json_encode($package->toArray()).','.PHP_EOL;
}
if (is_array($context) && !empty($context)) {
foreach ($context as $package) {
echo '"'.$package->name.'":'.json_encode($package->toArray()).','.PHP_EOL;
}
}

0 comments on commit e8d9d27

Please sign in to comment.