/**
  * Run method with main page logic
  * 
  * Read in list of the latest published events and populate template with results.
  * Display results in the page. Pagination enabled
  * @access public
  */
 public function run()
 {
     $PAGINATION_LIMIT = 10;
     $session = Session::getInstance();
     $user = $session->getUser();
     $eventDAO = EventDAO::getInstance();
     $page = isset($_GET["page"]) && is_numeric($_GET["page"]) ? intval($_GET["page"]) : 1;
     $platform_id = isset($_GET["platform"]) && is_numeric($_GET["platform"]) ? intval($_GET["platform"]) : 0;
     if ($page < 1) {
         $page = 1;
     }
     $count = $paginator = $paginator_page = $queryVars = $current_platform = null;
     if ($platform_id <= 0) {
         $count = $eventDAO->countStatus(Event::APPROVED_STATUS);
         $paginator = new Paginator($count, $PAGINATION_LIMIT);
         $paginator_page = $paginator->getPage($page);
         $event_array = $eventDAO->allByStatus(Event::APPROVED_STATUS, array("order" => "{$eventDAO->getTableName()}.date DESC, {$eventDAO->getTableName()}.id DESC", "joins" => true, "limit" => $paginator_page));
     } else {
         $count = $eventDAO->countPlatformStatus($platform_id, Event::APPROVED_STATUS);
         $paginator = new Paginator($count, $PAGINATION_LIMIT);
         $paginator_page = $paginator->getPage($page);
         $event_array = $eventDAO->allByPlatformStatus($platform_id, Event::APPROVED_STATUS, array("order" => "{$eventDAO->getTableName()}.date DESC, {$eventDAO->getTableName()}.id DESC", "joins" => true, "limit" => $paginator_page));
         $queryVars = array("platform" => $platform_id);
     }
     $platformDAO = PlatformDAO::getInstance();
     $platform_array = $platformDAO->all();
     //print_r ($event_array);
     if ($platform_id > 0) {
         $current_platform = $platformDAO->load($platform_id);
     }
     $this->template->render(array("title" => "Event List", "main_page" => "event_list_tpl.php", "event_array" => $event_array, "session" => $session, "paginator_page" => $paginator_page, "sidebar_extra" => joinPath("fragments", "event_sidebar_tpl.php"), "platform_array" => $platform_array, "queryVars" => $queryVars, "current_platform" => $current_platform));
 }
Exemple #2
0
function showHead($title = '')
{
    global $template, $config;
    ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head>
<title><?php 
    echo $title;
    ?>
</title>
<link href="<?php 
    echo joinPath($config['site_absolute_url'], '/');
    ?>
css/style.css" rel="stylesheet" type="text/css" />
<script src="<?php 
    echo joinPath($config['site_absolute_url'], '/');
    ?>
js/JSL.js" type="text/javascript"></script>
<script src="<?php 
    echo joinPath($config['site_absolute_url'], '/');
    ?>
js/application.js" type="text/javascript"></script>
<?php 
    echo implode($template->includes, "\n");
}
Exemple #3
0
function printEnd()
{
    global $template, $config;
    ?>
<!-- End Content -->
</div>
<div id="end">
<h1 id="logo"><a href="<?php 
    echo $config['site_url'];
    ?>
"><?php 
    echo $config['site_title'];
    ?>
</a></h1>
</div>

<script src="<?php 
    echo joinPath($config['site_url'], 'js/library/jsl.js');
    ?>
" type="text/javascript"></script>
<script src="<?php 
    echo joinPath($config['site_url'], 'js/application.js');
    ?>
" type="text/javascript"></script>
<?php 
    echo implode("\n", $template->js_includes);
    ?>
</body>
</html>
<?php 
}
Exemple #4
0
 /**
  * Constructor
  * Argument: $log_file - The file to which all the log message must be saved to.
  */
 function Logger($log_file = '')
 {
     global $config;
     $folder = joinPath($config['site_folder'], 'Logs');
     if (!$log_file) {
         //Log file not specifed - use default.
         if (file_exists($folder)) {
             $log_file = joinPath($folder, 'Development.log');
         }
     } else {
         //Use user specified log file
         if (file_exists($folder)) {
             $log_file = joinPath($folder, $log_file);
         }
     }
     $this->log_file = $log_file;
     if ($this->log_file and is_writable($folder)) {
         $this->handle = fopen($this->log_file, 'a');
     }
     if (!$this->handle) {
         print "Cannot enable logging: Log File '{$this->log_file}' not writable";
     }
 }
Exemple #5
0
/**
 * Read the plugin folder and put all the plugins found there in the dropdown menu
 */
function loadPlugins()
{
    global $config;
    $plugins = array();
    // Open plugin directory, and proceed to read its contents
    $dir = joinPath($config['site_folder'], 'plugins');
    $files = ls("*", $dir, false, array('return_folders'));
    foreach ($files as $file) {
        if ($file == 'CVS' . DIRECTORY_SEPARATOR || $file == '.' || $file == '..' || $file == 'api' . DIRECTORY_SEPARATOR || $file == '.svn' . DIRECTORY_SEPARATOR) {
            continue;
        }
        $plugins[] = substr($file, 0, -1);
        //Remove the trailing '/'
    }
    //Show the dropdown menu only if there are plugins
    if (count($plugins)) {
        print '<li class="dropdown"><a href="' . joinPath($config['site_relative_path'], 'plugins/') . '" class="plugin with-icon">Plugins</a>';
        print "\n<ul class='menu-with-icon plugins'>\n";
        foreach ($plugins as $plug) {
            print '<li><a href="' . joinPath($config['site_absolute_path'], 'plugins/', "{$plug}/") . '">' . format($plug) . '</a></li>' . "\n";
        }
        print '</ul></li>';
    }
}
<?php

/**
 * File defines the DeleteAlbumController PageController class
 * @package PageController
 */
/**
 */
$current_dir = dirname(__FILE__);
require_once $current_dir . DIRECTORY_SEPARATOR . "shared" . DIRECTORY_SEPARATOR . "bootstrap.php";
require_once joinPath(INCLUDES_DIR, "models", "Album.php");
require_once joinPath(INCLUDES_DIR, "models", "Photo.php");
/**
 * ADMIN PAGE. Interface for deleting an album entry
 * 
 * Display confirmation for album deletion. For POST request,
 * check user credentials, check if album exists and then delete entry from database.
 * Available to admins only.
 * @package PageController
 */
class DeleteAlbumController implements Controller
{
    protected $template;
    public function __construct()
    {
        $this->template = new PageTemplate();
    }
    public function run()
    {
        $session = Session::getInstance();
        $user = $session->getUser();
        ?>
</a></td>
<td><?php 
        echo $album->title;
        ?>
</td>
</tr>
        <?php 
        $i++;
    }
    ?>
        </tbody>
    </table>
    </form>
    <?php 
    include joinPath("fragments", "pagination_tpl.php");
} elseif (strcmp($action, "delete") == 0) {
    ?>
    <div id="breadcrumb_trail"><p><a href="album_options.php">Album Options</a></p></div>
    <h3>No albums selected</h3>
    <p>No albums chosen for deletion</p>
<?php 
} else {
    ?>
    <p style="float: right;"><a href="<?php 
    echo generate_link_url("create_album.php");
    ?>
">Create</a></p>
    <div id="breadcrumb_trail"><p><a href="album_options.php">Album Options</a></p></div>
    <h3>Album Options</h3>
    <div style="clear: both;"></div>
 /**
  * Run method with main page logic
  * 
  * Populate template and display form for editing an photo entry. For POST requests,
  * check user credentials, check if photo exists and then update entry in database.
  * Available to admins only
  * @access public
  */
 public function run()
 {
     $session = Session::getInstance();
     $user = $session->getUser();
     if (!$user || !$user->isAdmin()) {
         $session->setMessage("Do not have permission to access", Session::MESSAGE_ERROR);
         header("Location: " . BASE_URL);
         return;
     }
     $photoDAO = PhotoDAO::getInstance();
     $albumDAO = AlbumDAO::getInstance();
     $photo = null;
     $form_errors = array();
     $form_values = array("id" => "", "albumid" => "", "title" => "", "description" => "");
     if (!empty($_POST)) {
         $form_values["id"] = isset($_POST["id"]) && is_numeric($_POST["id"]) ? intval($_POST["id"]) : "";
         $form_values["albumid"] = isset($_POST["albumid"]) && is_numeric($_POST["albumid"]) ? intval($_POST["albumid"]) : "";
         $form_values["title"] = isset($_POST["title"]) ? trim($_POST["title"]) : "";
         $form_values["description"] = isset($_POST["description"]) ? trim($_POST["description"]) : "";
         if (empty($form_values["id"])) {
             $form_errors["id"] = "No id specified";
         }
         $photo = $photoDAO->load($form_values["id"]);
         if (!$photo) {
             $form_errors["id"] = "Photo does not exist";
         }
         if (empty($form_values["albumid"])) {
             $form_errors["albumid"] = "No albumid specified";
         } else {
             if (!$albumDAO->load($form_values["albumid"])) {
                 $form_errors["albumid"] = "Album does not exist";
             }
         }
         if (empty($form_values["title"])) {
             $form_errors["title"] = "No title specified";
         }
         if (empty($form_values["description"])) {
             $form_errors["description"] = "No description specified";
         }
         // Check if image will be changed
         $upload_path = "";
         if (!empty($_FILES["imagefile"]) && $_FILES["imagefile"]["error"] != UPLOAD_ERR_NO_FILE) {
             if ($_FILES["imagefile"]["error"] != UPLOAD_ERR_OK) {
                 $form_errors["imagefile"] = "File upload failed";
             } else {
                 $info = getimagesize($_FILES["imagefile"]["tmp_name"]);
                 $path = pathinfo($_FILES["imagefile"]["name"]);
                 $upload_path = joinPath(Photo::UPLOAD_DIR, strftime("%Y_%m"), basename($_FILES['imagefile']['name']));
                 $thumbLoc = joinPath(Photo::THUMBNAIL_DIR, strftime("%Y_%m"), $path["filename"] . "_thumb.jpg");
                 $smallThumbLoc = joinPath(Photo::THUMBNAIL_DIR, strftime("%Y_%m"), $path["filename"] . "_thumb_small.jpg");
                 if (!$info || !(strtolower($path["extension"]) != ".png" && strtolower($path["extension"]) != ".jpg" && strtolower($path["extension"]) != ".jpeg")) {
                     $form_errors["imagefile"] = "An invalid file was uploaded";
                 } else {
                     if (file_exists($upload_path)) {
                         unlink($upload_path);
                         if (file_exists($thumbLoc)) {
                             unlink($thumbLoc);
                         }
                         if (file_exists($smallThumbLoc)) {
                             unlink($smallThumbLoc);
                         }
                         //$form_errors["imagefile"] = "Filename already exists.  Please choose different name or delete file first";
                     }
                 }
             }
         }
         if (empty($form_errors)) {
             $photo->setAlbumId($form_values["albumid"]);
             $photo->setTitle($form_values["title"]);
             $photo->setDescription($form_values["description"]);
             // New image has been uploaded
             if (!empty($_FILES["imagefile"]) && $_FILES["imagefile"]["error"] != UPLOAD_ERR_NO_FILE) {
                 if (!file_exists(dirname($upload_path))) {
                     mkdir(dirname($upload_path));
                 }
                 if (move_uploaded_file($_FILES["imagefile"]["tmp_name"], $upload_path)) {
                     $photo->setFileLoc($upload_path);
                     // Reset thumbnail location in case new image does not need a thumbnail
                     $photo->setThumbLoc("");
                     // Create thumbnail
                     if ($info[0] > Photo::MAX_WIDTH) {
                         $phpThumb = new phpThumb();
                         $phpThumb->setSourceFilename($photo->getFileLoc());
                         $phpThumb->setParameter('w', Photo::MAX_WIDTH);
                         $phpThumb->setParameter('config_output_format', 'jpeg');
                         if (!file_exists(dirname($thumbLoc))) {
                             mkdir(dirname($thumbLoc));
                         }
                         if ($phpThumb->GenerateThumbnail() && $phpThumb->RenderToFile($thumbLoc)) {
                             $photo->setThumbLoc($thumbLoc);
                             $phpThumb = new phpThumb();
                             $phpThumb->setSourceFilename($photo->getFileLoc());
                             $phpThumb->setParameter('h', Photo::SMALL_THUMB_HEIGHT);
                             $phpThumb->setParameter('config_output_format', 'jpeg');
                             $phpThumb->GenerateThumbnail();
                         } else {
                             if (file_exists($photo->getFileLoc())) {
                                 unlink($photo->getFileLoc());
                             }
                             $form_errors["imagefile"] = "Image larger than " . Photo::MAX_WIDTH . "x" . Photo::MAX_HEIGHT . " and thumbnail generation failed";
                         }
                     }
                 } else {
                     $form_errors["imagefile"] = "File could not be moved";
                 }
             }
             if (empty($form_errors["imagefile"])) {
                 if ($photoDAO->save($photo)) {
                     $session->setMessage("Photo saved");
                     header("Location: edit_photo.php?id={$photo->getId()}");
                     return;
                 } else {
                     $session->setMessage("Photo not saved");
                 }
             }
         } else {
             if (empty($form_errors["id"])) {
                 $photo = $photoDAO->load($form_values["id"]);
             }
         }
     } else {
         if (!empty($_GET)) {
             $form_values["id"] = isset($_GET["id"]) ? $_GET["id"] : "";
             if (empty($form_values["id"])) {
                 header("Location: " . BASE_URL);
                 return;
             } else {
                 $photo = $photoDAO->load($form_values["id"]);
                 if ($photo) {
                     $form_values["id"] = $photo->getId();
                     $form_values["albumid"] = $photo->getAlbumId();
                     $form_values["title"] = $photo->getTitle();
                     $form_values["description"] = $photo->getDescription();
                 }
             }
         }
     }
     $album_array = $albumDAO->all();
     $this->template->render(array("title" => "Edit Photo", "session" => $session, "main_page" => "edit_photo_tpl.php", "photo" => $photo, "form_values" => $form_values, "form_errors" => $form_errors, "album_array" => $album_array));
 }
 function urlload($url, $options = array())
 {
     $default_options = array('method' => 'get', 'post_data' => false, 'return_info' => false, 'return_body' => true, 'cache' => false, 'referer' => '', 'headers' => array(), 'session' => false, 'session_close' => false);
     // Sets the default options.
     foreach ($default_options as $opt => $value) {
         if (!isset($options[$opt])) {
             $options[$opt] = $value;
         }
     }
     $url_parts = parse_url($url);
     $ch = false;
     $info = array('http_code' => 200);
     $response = '';
     $send_header = array('Accept' => 'text/*', 'User-Agent' => 'BinGet/1.00.A (http://www.bin-co.com/php/scripts/load/)') + $options['headers'];
     // Add custom headers provided by the user.
     if ($options['cache']) {
         $cache_folder = joinPath(sys_get_temp_dir(), 'php-load-function');
         if (isset($options['cache_folder'])) {
             $cache_folder = $options['cache_folder'];
         }
         if (!file_exists($cache_folder)) {
             $old_umask = umask(0);
             // Or the folder will not get write permission for everybody.
             mkdir($cache_folder, 0777);
             umask($old_umask);
         }
         $cache_file_name = md5($url) . '.cache';
         $cache_file = joinPath($cache_folder, $cache_file_name);
         //Don't change the variable name - used at the end of the function.
         if (file_exists($cache_file)) {
             // Cached file exists - return that.
             $response = file_get_contents($cache_file);
             //Seperate header and content
             $separator_position = strpos($response, "\r\n\r\n");
             $header_text = substr($response, 0, $separator_position);
             $body = substr($response, $separator_position + 4);
             foreach (explode("\n", $header_text) as $line) {
                 $parts = explode(": ", $line);
                 if (count($parts) == 2) {
                     $headers[$parts[0]] = chop($parts[1]);
                 }
             }
             $headers['cached'] = true;
             if (!$options['return_info']) {
                 return $body;
             } else {
                 return array('headers' => $headers, 'body' => $body, 'info' => array('cached' => true));
             }
         }
     }
     if (isset($options['post_data'])) {
         //There is an option to specify some data to be posted.
         $options['method'] = 'post';
         if (is_array($options['post_data'])) {
             //The data is in array format.
             $post_data = array();
             foreach ($options['post_data'] as $key => $value) {
                 $post_data[] = "{$key}=" . urlencode($value);
             }
             $url_parts['query'] = implode('&', $post_data);
         } else {
             //Its a string
             $url_parts['query'] = $options['post_data'];
         }
     } elseif (isset($options['multipart_data'])) {
         //There is an option to specify some data to be posted.
         $options['method'] = 'post';
         $url_parts['query'] = $options['multipart_data'];
         /*
            This array consists of a name-indexed set of options.
            For example,
            'name' => array('option' => value)
            Available options are:
            filename: the name to report when uploading a file.
            type: the mime type of the file being uploaded (not used with curl).
            binary: a flag to tell the other end that the file is being uploaded in binary mode (not used with curl).
            contents: the file contents. More efficient for fsockopen if you already have the file contents.
            fromfile: the file to upload. More efficient for curl if you don't have the file contents.
         
            Note the name of the file specified with fromfile overrides filename when using curl.
         */
     }
     ///////////////////////////// Curl /////////////////////////////////////
     //If curl is available, use curl to get the data.
     if (function_exists("curl_init") and !(isset($options['use']) and $options['use'] == 'fsocketopen')) {
         //Don't use curl if it is specifically stated to use fsocketopen in the options
         if (isset($options['post_data'])) {
             //There is an option to specify some data to be posted.
             $page = $url;
             $options['method'] = 'post';
             if (is_array($options['post_data'])) {
                 //The data is in array format.
                 $post_data = array();
                 foreach ($options['post_data'] as $key => $value) {
                     $post_data[] = "{$key}=" . urlencode($value);
                 }
                 $url_parts['query'] = implode('&', $post_data);
             } else {
                 //Its a string
                 $url_parts['query'] = $options['post_data'];
             }
         } else {
             if (isset($options['method']) and $options['method'] == 'post') {
                 $page = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];
             } else {
                 $page = $url;
             }
         }
         if ($options['session'] and isset($GLOBALS['_binget_curl_session'])) {
             $ch = $GLOBALS['_binget_curl_session'];
         } else {
             $ch = curl_init($url_parts['host']);
         }
         curl_setopt($ch, CURLOPT_URL, $page) or die("Invalid cURL Handle Resouce");
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         //Just return the data - not print the whole thing.
         curl_setopt($ch, CURLOPT_HEADER, true);
         //We need the headers
         curl_setopt($ch, CURLOPT_NOBODY, !$options['return_body']);
         //The content - if true, will not download the contents. There is a ! operation - don't remove it.
         $tmpdir = NULL;
         //This acts as a flag for us to clean up temp files
         if (isset($options['method']) and $options['method'] == 'post' and isset($url_parts['query'])) {
             curl_setopt($ch, CURLOPT_POST, true);
             if (is_array($url_parts['query'])) {
                 //multipart form data (eg. file upload)
                 $postdata = array();
                 foreach ($url_parts['query'] as $name => $data) {
                     if (isset($data['contents']) && isset($data['filename'])) {
                         if (!isset($tmpdir)) {
                             //If the temporary folder is not specifed - and we want to upload a file, create a temp folder.
                             //  :TODO:
                             $dir = sys_get_temp_dir();
                             $prefix = 'load';
                             if (substr($dir, -1) != '/') {
                                 $dir .= '/';
                             }
                             do {
                                 $path = $dir . $prefix . mt_rand(0, 9999999);
                             } while (!mkdir($path, $mode));
                             $tmpdir = $path;
                         }
                         $tmpfile = $tmpdir . '/' . $data['filename'];
                         file_put_contents($tmpfile, $data['contents']);
                         $data['fromfile'] = $tmpfile;
                     }
                     if (isset($data['fromfile'])) {
                         // Not sure how to pass mime type and/or the 'use binary' flag
                         $postdata[$name] = '@' . $data['fromfile'];
                     } elseif (isset($data['contents'])) {
                         $postdata[$name] = $data['contents'];
                     } else {
                         $postdata[$name] = '';
                     }
                 }
                 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
             } else {
                 curl_setopt($ch, CURLOPT_POSTFIELDS, $url_parts['query']);
             }
         }
         //Set the headers our spiders sends
         curl_setopt($ch, CURLOPT_USERAGENT, $send_header['User-Agent']);
         //The Name of the UserAgent we will be using ;)
         $custom_headers = array("Accept: " . $send_header['Accept']);
         if (isset($options['modified_since'])) {
             array_push($custom_headers, "If-Modified-Since: " . gmdate('D, d M Y H:i:s \\G\\M\\T', strtotime($options['modified_since'])));
         }
         curl_setopt($ch, CURLOPT_HTTPHEADER, $custom_headers);
         if ($options['referer']) {
             curl_setopt($ch, CURLOPT_REFERER, $options['referer']);
         }
         curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/binget-cookie.txt");
         //If ever needed...
         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
         curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
         $custom_headers = array();
         unset($send_header['User-Agent']);
         // Already done (above)
         foreach ($send_header as $name => $value) {
             if (is_array($value)) {
                 foreach ($value as $item) {
                     $custom_headers[] = "{$name}: {$item}";
                 }
             } else {
                 $custom_headers[] = "{$name}: {$value}";
             }
         }
         if (isset($url_parts['user']) and isset($url_parts['pass'])) {
             $custom_headers[] = "Authorization: Basic " . base64_encode($url_parts['user'] . ':' . $url_parts['pass']);
         }
         curl_setopt($ch, CURLOPT_HTTPHEADER, $custom_headers);
         $response = curl_exec($ch);
         if (isset($tmpdir)) {
             //rmdirr($tmpdir); //Cleanup any temporary files :TODO:
         }
         $info = curl_getinfo($ch);
         //Some information on the fetch
         if ($options['session'] and !$options['session_close']) {
             $GLOBALS['_binget_curl_session'] = $ch;
         } else {
             curl_close($ch);
         }
         //If the session option is not set, close the session.
         //////////////////////////////////////////// FSockOpen //////////////////////////////
     } else {
         //If there is no curl, use fsocketopen - but keep in mind that most advanced features will be lost with this approch.
         if (!isset($url_parts['query']) || (isset($options['method']) and $options['method'] == 'post')) {
             $page = $url_parts['path'];
         } else {
             $page = $url_parts['path'] . '?' . $url_parts['query'];
         }
         if (!isset($url_parts['port'])) {
             $url_parts['port'] = $url_parts['scheme'] == 'https' ? 443 : 80;
         }
         $host = ($url_parts['scheme'] == 'https' ? 'ssl://' : '') . $url_parts['host'];
         $fp = fsockopen($host, $url_parts['port'], $errno, $errstr, 30);
         if ($fp) {
             $out = '';
             if (isset($options['method']) and $options['method'] == 'post' and isset($url_parts['query'])) {
                 $out .= "POST {$page} HTTP/1.1\r\n";
             } else {
                 $out .= "GET {$page} HTTP/1.0\r\n";
                 //HTTP/1.0 is much easier to handle than HTTP/1.1
             }
             $out .= "Host: {$url_parts['host']}\r\n";
             foreach ($send_header as $name => $value) {
                 if (is_array($value)) {
                     foreach ($value as $item) {
                         $out .= "{$name}: {$item}\r\n";
                     }
                 } else {
                     $out .= "{$name}: {$value}\r\n";
                 }
             }
             $out .= "Connection: Close\r\n";
             //HTTP Basic Authorization support
             if (isset($url_parts['user']) and isset($url_parts['pass'])) {
                 $out .= "Authorization: Basic " . base64_encode($url_parts['user'] . ':' . $url_parts['pass']) . "\r\n";
             }
             //If the request is post - pass the data in a special way.
             if (isset($options['method']) and $options['method'] == 'post') {
                 if (is_array($url_parts['query'])) {
                     //multipart form data (eg. file upload)
                     // Make a random (hopefully unique) identifier for the boundary
                     srand((double) microtime() * 1000000);
                     $boundary = "---------------------------" . substr(md5(rand(0, 32000)), 0, 10);
                     $postdata = array();
                     $postdata[] = '--' . $boundary;
                     foreach ($url_parts['query'] as $name => $data) {
                         $disposition = 'Content-Disposition: form-data; name="' . $name . '"';
                         if (isset($data['filename'])) {
                             $disposition .= '; filename="' . $data['filename'] . '"';
                         }
                         $postdata[] = $disposition;
                         if (isset($data['type'])) {
                             $postdata[] = 'Content-Type: ' . $data['type'];
                         }
                         if (isset($data['binary']) && $data['binary']) {
                             $postdata[] = 'Content-Transfer-Encoding: binary';
                         } else {
                             $postdata[] = '';
                         }
                         if (isset($data['fromfile'])) {
                             $data['contents'] = file_get_contents($data['fromfile']);
                         }
                         if (isset($data['contents'])) {
                             $postdata[] = $data['contents'];
                         } else {
                             $postdata[] = '';
                         }
                         $postdata[] = '--' . $boundary;
                     }
                     $postdata = implode("\r\n", $postdata) . "\r\n";
                     $length = strlen($postdata);
                     $postdata = 'Content-Type: multipart/form-data; boundary=' . $boundary . "\r\n" . 'Content-Length: ' . $length . "\r\n" . "\r\n" . $postdata;
                     $out .= $postdata;
                 } else {
                     $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
                     $out .= 'Content-Length: ' . strlen($url_parts['query']) . "\r\n";
                     $out .= "\r\n" . $url_parts['query'];
                 }
             }
             $out .= "\r\n";
             fwrite($fp, $out);
             while (!feof($fp)) {
                 $response .= fgets($fp, 128);
             }
             fclose($fp);
         }
     }
     //Get the headers in an associative array
     $headers = array();
     if ($info['http_code'] == 404) {
         $body = "";
         $headers['Status'] = 404;
     } else {
         //Seperate header and content
         $header_text = substr($response, 0, $info['header_size']);
         $body = substr($response, $info['header_size']);
         foreach (explode("\n", $header_text) as $line) {
             $parts = explode(": ", $line);
             if (count($parts) == 2) {
                 if (isset($headers[$parts[0]])) {
                     if (is_array($headers[$parts[0]])) {
                         $headers[$parts[0]][] = chop($parts[1]);
                     } else {
                         $headers[$parts[0]] = array($headers[$parts[0]], chop($parts[1]));
                     }
                 } else {
                     $headers[$parts[0]] = chop($parts[1]);
                 }
             }
         }
     }
     if (isset($cache_file)) {
         //Should we cache the URL?
         file_put_contents($cache_file, $response);
     }
     if ($options['return_info']) {
         return array('headers' => $headers, 'body' => $body, 'info' => $info, 'curl_handle' => $ch);
     }
     return $body;
 }
 /**
  * Run method with main page logic
  * 
  * Populate template and display form for registration. For POST requests, check if the user
  * already exists. If not, create new User and AuthToken entries and send an email notification to the user
  * @access public
  */
 public function run()
 {
     $form_errors = array();
     $form_values = array("username" => "", "password" => "", "password2" => "", "ulid" => "");
     $session = Session::getInstance();
     $user = $session->getUser();
     // Session should not have a defined user
     if ($user != null) {
         $session->setMessage("You are already a user", Session::MESSAGE_ERROR);
         header("Location: " . BASE_URL);
         return;
     }
     if (!empty($_POST)) {
         $form_values["username"] = isset($_POST["username"]) ? trim($_POST["username"]) : "";
         $form_values["password"] = isset($_POST["password"]) ? trim($_POST["password"]) : "";
         $form_values["password2"] = isset($_POST["password2"]) ? trim($_POST["password2"]) : "";
         $form_values["ulid"] = isset($_POST["ulid"]) ? trim($_POST["ulid"]) : "";
         if (empty($form_values["username"])) {
             $form_errors["username"] = "******";
         }
         if (empty($form_values["password"])) {
             $form_errors["password"] = "******";
         }
         if (empty($form_values["password2"])) {
             $form_errors["password"] = "******";
         }
         if (empty($form_values["ulid"])) {
             $form_errors["ulid"] = "No ulid specified";
         } else {
             if (!preg_match("/[a-z]{5,7}/", $form_values["ulid"])) {
                 $form_errors["ulid"] = "Ulid is not in the proper format.";
             }
         }
         $userDAO = UserDAO::getInstance();
         $user = $userDAO->loadByUsername($form_values["username"]);
         // User already exists
         if ($user != null) {
             $form_errors["username"] = "******";
         }
         if (strcmp($form_values["password"], $form_values["password2"]) != 0) {
             $form_errors["password"] = "******";
         }
         $user = $userDAO->loadByUlid($form_values["ulid"]);
         // User already exists
         if ($user != null) {
             $form_errors["ulid"] = "Ulid is already registered";
         }
         if (empty($form_errors)) {
             $user = new User();
             $user->setUsername($form_values["username"]);
             $user->setPassHash(sha1($form_values["password"]));
             $user->setUlid($form_values["ulid"]);
             $status = $userDAO->insert($user);
             if ($status) {
                 $token = new AuthToken();
                 $token->setUser($user);
                 $tokenDAO = AuthTokenDAO::getInstance();
                 $status = $tokenDAO->insert($token);
                 if ($status) {
                     $session->setMessage("Registration started. Check your email for a message to continue");
                     if (defined("SMTP_HOST") && strcmp(SMTP_HOST, "") != 0) {
                         $from_addr = EMAIL_ADDRESS;
                         //$to = "*****@*****.**";
                         $to = "{$form_values["ulid"]}@" . User::ISU_EMAIL_DOMAIN;
                         $subject = "Verify registration with " . SITE_NAME;
                         $body = "To start the next step of the registration process, click the verify link below and enter the requested information. If the URL does not appear as a link, copy the URL, paste it into your browser's address bar and proceed to the web page.\n\n" . joinPath(BASE_URL, "verify.php") . "?token={$token->getToken()}\n";
                         $headers = array("From" => $from_addr, "To" => $to, "Subject" => $subject);
                         $stmp = Mail::factory("smtp", array("host" => SMTP_HOST, "auth" => true, "username" => SMTP_USERNAME, "password" => SMTP_PASSWORD));
                         $mail = $stmp->send($to, $headers, $body);
                     }
                     header("Location: " . BASE_URL);
                     return;
                 }
             }
         }
     }
     $user = $session->getUser();
     $this->template->render(array("title" => "Register", "main_page" => "register_tpl.php", "user" => $user, "session" => $session, "form_errors" => $form_errors, "form_values" => $form_values));
 }
<?php

/**
 * File defines the CreateAlbumController PageController class
 * @package PageController
 */
/**
 */
$current_dir = dirname(__FILE__);
require_once $current_dir . DIRECTORY_SEPARATOR . "shared" . DIRECTORY_SEPARATOR . "bootstrap.php";
require_once joinPath(INCLUDES_DIR, "models", "Album.php");
/**
 * ADMIN PAGE. Interface for creating a new album entry
 *
 * Display form for creating a new album entry. For POST request,
 * validate form data and save information to database. Available to admins only
 * @package PageController
 */
class CreateAlbumController implements Controller
{
    /**
     * PageTemplate object used to render page
     * @access protected
     * @var PageTemplate
     */
    protected $template;
    /**
     * Constructor. Create instance of PageTemplate using default index_tpl.php file
     * @access public
     */
    public function __construct()
Exemple #12
0
$crud->allow['add'] = false;
// $crud->allow['edit'] = false;
$crud->allow['sorting'] = false;
$all_donation_types = array('ecs' => 'ECS', 'globalgiving' => 'Global Giving', 'online' => 'Online', 'other' => "Other", 'any' => 'Any');
$all_donation_status = array('TO_BE_APPROVED_BY_POC' => 'Not Deposited', 'DEPOSIT COMPLETE' => 'Deposited', 'any' => 'Any');
$all_cities = $sql->getById("SELECT id,name FROM cities ORDER BY name");
$all_cities[0] = 'Any';
// Filtering code - goes on the top.
$html = new HTML();
$html->options['output'] = 'return';
$crud->code['before_content'] = '<form action="donations.php" method="post" class="form-area">' . $html->buildInput("city_id", 'City', 'select', $city_id, array('options' => $all_cities)) . '<div id="select-date-area">' . $html->buildInput("donation_type", 'Type', 'select', $donation_type, array('options' => $all_donation_types)) . $html->buildInput("donation_status", 'Status', 'select', $donation_status, array('options' => $all_donation_status)) . $html->buildInput('from', 'From', 'text', $from, array('class' => 'date-picker')) . $html->buildInput('to', 'To', 'text', $to, array('class' => 'date-picker')) . '</div><a href="#" id="select-date-toggle">More Options</a><br />' . $html->buildInput("action", '&nbsp;', 'submit', 'Filter', array('class' => 'btn btn-primary')) . '</form><br /><br />';
$html->options['output'] = 'print';
// The SQL for the listing
$crud->setListingQuery("SELECT D.* FROM external_donations D \n\tINNER JOIN users U ON U.id=D.fundraiser_id\n\tWHERE " . implode(" AND ", $checks) . " ORDER BY D.created_at DESC");
// Fields customization.
$crud->addField("donation_type", 'Type', 'enum', array(), $all_donation_types, 'select');
$all_donation_status_without_any = $all_donation_status;
unset($all_donation_status_without_any['any']);
$crud->addField("donation_status", 'Donation Status', 'enum', array(), $all_donation_status_without_any, 'select');
$crud->addListDataField("donor_id", "donours", "Donor", "", array('fields' => 'id,first_name'));
$crud->fields['donor_id']['extra_info']['readonly'] = true;
$crud->addListDataField("fundraiser_id", "users", "Fundraiser", "", array('fields' => 'id,CONCAT(first_name, " ", last_name) AS name'));
$crud->fields['fundraiser_id']['extra_info']['readonly'] = true;
$crud->addListingField('Status', array('html' => '($row["donation_status"] == "DEPOSIT COMPLETE")' . ' ? "<span class=\\"with-icon success\\">Deposited - <a href=\'?status_action=disapprove&select_row[]=$row[id]\'>Undo Approval?</a></span>"' . ' : "<span class=\\"with-icon error\\">Not Deposited Yet - <a href=\'?status_action=approve&select_row[]=$row[id]\'>Approve?</a></span>"'));
// Show only the listing
$crud->setListingFields("donation_type", "amount", "donor_id", "fundraiser_id", "created_at", 'status');
$crud->setSearchFields('amount', 'donor_id', 'fundraiser_id');
// The other includes
$template->addResource(joinPath($config['site_url'], 'bower_components/jquery-ui/ui/minified/jquery-ui.min.js'), 'js', true);
$template->addResource(joinPath($config['site_url'], 'bower_components/jquery-ui/themes/base/minified/jquery-ui.min.css'), 'css', true);
render();
Exemple #13
0
</a>
	</div>
	<div class="collapse navbar-collapse">
		<ul class="nav navbar-nav pull-right">
			<li><a class="home with-icon" href="<?php 
echo $config['site_url'];
?>
">Home</a></li>
			<?php 
if ($current_folder != $base_folder) {
    ?>
<li><a class="folder with-icon" href="<?php 
    echo $config['site_url'];
    ?>
index.php?folder=<?php 
    echo joinPath($folder, '..');
    ?>
">Up</a></li><?php 
}
?>
		</ul>
	</div>

</div>
</div>

<div id="content" class="container">

<div class="message-area" id="error-message" <?php 
echo $QUERY['error'] ? '' : 'style="display:none;"';
?>
Exemple #14
0
<?php

require_once joinPath($config['site_folder'], 'models/Task.php');
require_once joinPath($config['site_folder'], 'models/User.php');
$User = new User();
checkUser();
//////////////////////////////////// Authenitication Checks ////////////////////////////////////
function checkUser($redirect = true)
{
    global $config;
    if (isset($config['single_user']) and $config['single_user']) {
        $_SESSION['user_id'] = $config['single_user'];
        return true;
    }
    if (!isset($_SESSION['user_id']) or !$_SESSION['user_id']) {
        if ($redirect) {
            showMessage("Please login to use this feature", $config['site_url'] . 'user/login.php', "error");
        }
        return false;
    }
    return true;
}
/// See if the given task's owner is the currently logined user.
function checkTaskOwnership($task_id, $return_only = false)
{
    global $sql;
    if (empty($_SESSION['user_id'])) {
        $correct_owner = 0;
    } else {
        $task_owner = $sql->getOne("SELECT user_id FROM Task WHERE id={$task_id}");
        $correct_owner = $task_owner == $_SESSION['user_id'];
}
?>
 for="published">Published:</label><select name="published" id="published"><option value="false"<?php 
if ($form_values["published"] == "false") {
    echo "selected=\"selected\"";
}
?>
>False</option><option value="true"<?php 
if ($form_values["published"] == "true") {
    echo "selected=\"selected\"";
}
?>
>True</option></select></li>
        <li><label <?php 
if (!empty($form_errors["tags"])) {
    ?>
class="error" <?php 
}
?>
 for="tags">Tags:</label><input type="text" name="tags" id="tags" value="<?php 
echo full_escape($form_values["tags"]);
?>
" /><p class="help_text">Space-separated string (ex: ssf4 blazblue tekken6)</p></li>
        <li class="submit"><input type="submit" value="Submit" /></li>
</ul>
</form>
<?php 
include joinPath("fragments", "tinymce_tpl.php");
$dateField = "postDate";
include joinPath("fragments", "jscal2_tpl.php");
Exemple #16
0
<?php

include 'common.php';
$img_file = joinPath($base_folder, $QUERY['file']);
$md5 = md5($img_file);
$ext = pathinfo($img_file, PATHINFO_EXTENSION);
$cache_file = joinPath($config['site_folder'], 'cache', $md5 . '.' . $ext);
if (file_exists($cache_file)) {
    $content_type = mime_content_type($cache_file);
    header("Content-type: " . $content_type);
    print file_get_contents($cache_file);
} else {
    $img = new Image($img_file);
    $img->resize(200, 0, false);
    $img->save($cache_file);
    $img->show();
}
 /**
  * Run method with main page logic
  * 
  * Reads in events for a given month or current month if no parameters are passed.
  * Allow filtering by platform id. Populate template and display event data in a calendar view on the page.
  * @access public
  */
 public function run()
 {
     $PAGINATION_LIMIT = 10;
     $session = Session::getInstance();
     $user = $session->getUser();
     $eventDAO = EventDAO::getInstance();
     $platformDAO = PlatformDAO::getInstance();
     //$page = (isset ($_GET["page"]) && is_numeric ($_GET["page"])) ? intval ($_GET["page"]) : 1;
     $platform_id = isset($_GET["platform"]) && is_numeric($_GET["platform"]) ? intval($_GET["platform"]) : 0;
     $month = isset($_GET["month"]) && is_numeric($_GET["month"]) ? intval($_GET["month"]) : 0;
     $year = isset($_GET["year"]) && is_numeric($_GET["year"]) ? intval($_GET["year"]) : 0;
     //if ($page < 1) {
     //    $page = 1;
     //}
     $count = $paginator = $paginator_page = $event_array = $next_eventday = $prev_eventday = $current_platform = null;
     if ($platform_id > 0 && checkdate($month, 1, $year)) {
         $start = mktime(0, 0, 0, $month, 1, $year);
         $end = strtotime("+1 month", $start) - 1;
         //$count = $eventDAO->countPlatformStatusAndRange ($platform, Event::APPROVED_STATUS, $start, $end);
         //$paginator = new Paginator ($count, 3);
         //$paginator_page = $paginator->getPage ($page);
         $event_array = $eventDAO->allByPlatformStatusAndRange($platform_id, Event::APPROVED_STATUS, $start, $end, array("order" => "{$eventDAO->getTableName()}.date DESC, {$eventDAO->getTableName()}.id DESC", "joins" => true));
     } else {
         if ($platform_id > 0) {
             $start = mktime(0, 0, 0, idate("m"), 1, idate("Y"));
             $end = strtotime("+1 month", $start) - 1;
             //$count = $eventDAO->countPlatformStatusAndRange ($platform, Event::APPROVED_STATUS, $start, $end);
             //$paginator = new Paginator ($count, 3);
             //$paginator_page = $paginator->getPage ($page);
             $event_array = $eventDAO->allByPlatformStatusAndRange($platform_id, Event::APPROVED_STATUS, $start, $end, array("order" => "{$eventDAO->getTableName()}.date DESC, {$eventDAO->getTableName()}.id DESC", "joins" => true));
         } else {
             if (checkdate($month, 1, $year)) {
                 $start = mktime(0, 0, 0, $month, 1, $year);
                 $end = strtotime("+1 month", $start) - 1;
                 //$count = $eventDAO->countStatus (Event::APPROVED_STATUS);
                 //$paginator = new Paginator ($count, 3);
                 //$paginator_page = $paginator->getPage ($page);
                 $event_array = $eventDAO->allByStatusAndRange(Event::APPROVED_STATUS, $start, $end, array("order" => "{$eventDAO->getTableName()}.date DESC, {$eventDAO->getTableName()}.id DESC", "joins" => true));
             } else {
                 $start = mktime(0, 0, 0, idate("m"), 1, idate("Y"));
                 $end = strtotime("+1 month", $start) - 1;
                 //$count = $eventDAO->countStatus (Event::APPROVED_STATUS);
                 //$paginator = new Paginator ($count, 3);
                 //$paginator_page = $paginator->getPage ($page);
                 $event_array = $eventDAO->allByStatusAndRange(Event::APPROVED_STATUS, $start, $end, array("order" => "{$eventDAO->getTableName()}.date DESC, {$eventDAO->getTableName()}.id DESC", "joins" => true));
             }
         }
     }
     $next_eventday = $eventDAO->loadByNextDay($end, Event::APPROVED_STATUS);
     $prev_eventday = $eventDAO->loadByPreviousDay($start, Event::APPROVED_STATUS);
     if ($platform_id > 0) {
         $current_platform = $platformDAO->load($platform_id);
     }
     $platform_array = $platformDAO->all();
     //print_r ($event_array);
     $this->template->render(array("title" => "Event Month Calendar - " . date("F", $start) . " " . date("Y", $start), "main_page" => "events_month_tpl.php", "event_array" => $event_array, "session" => $session, "start" => $start, "end" => $end, "next_eventday" => $next_eventday, "prev_eventday" => $prev_eventday, "sidebar_extra" => joinPath("fragments", "event_sidebar_tpl.php"), "platform_array" => $platform_array, "current_platform" => $current_platform));
 }
 /**
  * Return the edit URL of the user
  *
  * @access public
  * @return string
  */
 public function getEditProfileUrl()
 {
     return joinPath(BASE_URL, "edit_profile.php?id={$this->id}");
 }
 /**
  * Constructor. Create instance of PageTemplate using default index_tpl.php file
  * @access public
  */
 public function __construct()
 {
     $this->template = new PageTemplate(joinPath("feeds", "events_ical_tpl.php"));
 }
Exemple #20
0
$locale = $sql->getOne("SELECT value FROM {$config['db_prefix']}Setting WHERE name='Locale' AND user_id={$user}");
if (!$locale) {
    //If the user has not set a locale, it uses the default locale set in the configuration.php file
    if (!isset($config['locale'])) {
        $locale = 'en_EN';
    } else {
        $locale = $config['locale'];
    }
}
$lang = reset(explode("_", $locale));
if (!$lang) {
    $lang = 'en';
}
// User wants a non-english version of the page.
if (isset($locale) and $locale and $locale != 'en_EN') {
    include joinPath($config['site_folder'], 'includes', 'locale', $locale . '.php');
}
$all_types = array('Immediately' => t('Immediately'), 'Someday/Maybe' => t('Someday/Maybe'), 'Waiting' => t('Waiting'), 'Idea' => t('Idea'), 'Done' => t('Done'));
$pending_projects = array();
$contexts = array();
$projects = array();
if (isset($_SESSION['user']) and is_numeric($_SESSION['user'])) {
    $QUERY['user_id'] = $_SESSION['user'];
    //Get active projects only - projects with tasks in them
    $qry_active_projects = "SELECT Project.id,Project.name FROM {$config['db_prefix']}Project AS Project" . " INNER JOIN {$config['db_prefix']}Task AS Task ON Task.project_id=Project.id WHERE Task.type='Immediately' AND Project.user_id={$_SESSION['user']}" . " GROUP BY Project.id LIMIT 0,10 ";
    $pending_projects = $sql->getById($qry_active_projects);
    //All Contexts for this user
    $contexts = $sql->getById("SELECT id,name FROM {$config['db_prefix']}Context WHERE user_id={$_SESSION['user']}");
    //All Projects for this user
    $projects = $sql->getById("SELECT id,name FROM {$config['db_prefix']}Project WHERE user_id='{$_SESSION['user']}'");
    //All the reminders for TODAY
 /**
  * Render a PHP/(X)HTML page with any values from the $data_array param
  *
  * $data_array must be in the form of an associative array with key => value pairs for variables.
  * The key will be the name of the variable used to access a value in the template file with the
  * value being the defined value set from value. The array will run through the extract
  * function to produce the requested variables.
  * @access public
  * @param array $data_array Associative array with key => value pairs to be extracted to the template
  */
 public function render($data_array = null)
 {
     if (is_array($data_array)) {
         $this->data_array = array_merge($this->data_array, $data_array);
     }
     // Import template specific functions. Only in scope for duration of render
     require_once joinPath(INCLUDES_DIR, self::$TPL_FUNCS_FILE);
     // Allow template object to be called through $template variable
     // along with the $this variable
     global $template;
     $template = $this;
     // Extra variables from data array for use in templates.
     // Avoids using array syntax to grab variables in template
     // files
     extract($this->data_array);
     // Import template file. Include is used in the case of fragments being
     // loaded multiple times
     include joinPath(TEMPLATE_DIR, $this->template_file);
 }
Exemple #22
0
 function fetchComics()
 {
     global $sql;
     $show_details = true;
     $image_extensions = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
     $where = '';
     if ($this->fetch_comics) {
         //User have specified a set of comics to download.
         $all_comics = $sql->getAll("SELECT id, name, feed, url,type, last_downloaded_on FROM Comic WHERE id IN (" . implode(',', $this->fetch_comics) . ')');
     } else {
         $all_comics = $sql->getAll("SELECT id, name, feed, url, type, last_downloaded_on FROM Comic WHERE status='1' AND\n\t\t\t\t(DATE_FORMAT(DATE_ADD(latest_comic_fetched_on, INTERVAL update_frequency DAY),'%Y-%m-%d' ) <= CURDATE() " . " OR latest_comic_fetched_on='0000-00-00 00:00:00')");
     }
     $total_comics = count($all_comics);
     $comic_count = 1;
     foreach ($all_comics as $feed) {
         if ($show_details) {
             print "{$comic_count}/{$total_comics}) {$feed['name']}({$feed['id']}) ... ";
         }
         $comic_count++;
         // Get the feed.
         if (!$feed['feed']) {
             continue;
         }
         $feed_details = load($feed['feed'], array('return_info' => true, 'modified_since' => $feed['last_downloaded_on']));
         $feed_contents = $feed_details['body'];
         $headers = $feed_details['headers'];
         $info = $feed_details['info'];
         if (!$feed_contents) {
             if ($show_details) {
                 print "No new items\n";
             }
             continue;
             //No content - means it have not been modified.
         }
         // Save last_modified to the db so that we don't have to download unnecessary stuff.
         $sql->execQuery("UPDATE Comic SET last_downloaded_on=NOW() WHERE id={$feed['id']}");
         if ($show_details) {
             print "downloaded ... ";
         }
         // Only RSS supported right now.
         $data = xml2array($feed_contents);
         if (!isset($data['rss']['channel']['item'])) {
             print "Cannot parse\n";
             continue;
         }
         $items = $data['rss']['channel']['item'];
         if (!isset($items[0])) {
             $items = array($items);
         }
         // Just 1 item in the feed. This is a ugly workaround for that.
         // We use a different query to get the regexps - we don't want it to be stripslashed.
         $regexps = $sql->getAssoc("SELECT title_match_regexp, fetch_regexp FROM Comic WHERE id={$feed['id']}", array('strip_slashes' => false));
         $feed['title_match_regexp'] = $this->escapeRegExpChars($regexps['title_match_regexp']);
         $feed['fetch_regexp'] = $this->escapeRegExpChars($regexps['fetch_regexp']);
         // Get the GUID and Image URL of all the latest strips in this comic. We can use this array to make sure that duplicates are not included.
         $last_strip = count($items) - 1;
         $last_time = $this->getMysqlTime(i($items[$last_strip], 'pubDate'));
         list($guids_of_latest_strips, $image_url_of_latest_strips) = $this->getStripList($feed['id'], $last_time);
         // Go thru all the posts in the feed and find the necessary details for the strip.
         foreach ($items as $strip) {
             if ($feed['title_match_regexp'] and $strip['title']) {
                 // Make sure that this feed item is a comic - some comics have content and comic in the same feed - but they usually have a word in the title like 'Comic' to specify that its a comic.
                 if ($feed['title_match_regexp'][0] == '/' and !preg_match("{$feed['title_match_regexp']}", $strip['title'])) {
                     continue;
                 } else {
                     if (strpos($feed['title_match_regexp'], $strip['title'])) {
                         continue;
                     }
                 }
             }
             if (isset($strip['guid']) and $strip['guid']) {
                 // Make sure we dont have this comic already.
                 if (in_array($strip['guid'], $guids_of_latest_strips)) {
                     if ($show_details) {
                         print "Done\n";
                     }
                     continue 2;
                     // Go to the next comic(not next strip).
                 }
             } else {
                 $strip['guid'] = '';
             }
             $image_url = '';
             //The comic image url.
             $contents = '';
             $time = date('Y-m-d H:i:s');
             if (i($strip, 'content:encoded')) {
                 $contents = i($strip, 'content:encoded');
             } elseif (i($strip, 'content')) {
                 $contents = i($strip, 'content');
             } else {
                 $contents = i($strip, 'description');
             }
             if (is_array($contents)) {
                 $contents = implode('', $contents);
             }
             // Sometimes this happens.
             if ($feed['type'] == 'embedded') {
                 $image_url = $this->findFirstImage($contents);
             }
             if (!$image_url and isset($strip['link']) and $strip['link']) {
                 // Most likely the image is available only on the site - not in the feed.
                 // In some comics, the link is a direct link to the image.
                 $ext_arr = split("\\.", basename($strip['link']));
                 $extension = '';
                 if (count($ext_arr) == 2) {
                     $extension = $ext_arr[1];
                 }
                 if (in_array($extension, $image_extensions)) {
                     //Yes, its an image extension.
                     $image_url = $strip['link'];
                 } else {
                     $strip_contents = load($strip['link']);
                     $image_url = $this->findComicImage($strip_contents, $feed['fetch_regexp']);
                 }
             }
             if ($image_url) {
                 if (strpos($image_url, 'http://') !== 0) {
                     $image_url = joinPath($feed['url'], $image_url);
                 }
                 //Its a relative path. Make it absolute.
             } else {
                 if (isset($strip['link'])) {
                     print " NO IMAGE FOUND FOR {$strip['link']}\n";
                 } elseif (isset($strip['title'])) {
                     print " NO IMAGE FOR {$strip['title']}\n";
                 } else {
                     print " NO IMAGE FOUND\n";
                 }
                 continue;
             }
             if (!isset($strip['pubDate']) or !$strip['pubDate']) {
                 $strip['pubDate'] = $time = date('Y-m-d H:i:s');
             } else {
                 $time = date('Y-m-d H:i:s', strtotime(i($strip, 'pubDate')));
             }
             if ($time < $last_time) {
                 // The posts are not in order - get all the strips of this comic - not just the lastest.
                 list($guids_of_latest_strips, $image_url_of_latest_strips, $last_time) = $this->getStripList($feed['id']);
             }
             $image_url = trim($image_url);
             // REALLY?!
             $already_have = in_array($image_url, $image_url_of_latest_strips);
             // Make sure that the strip is not duplicated.
             if (!$already_have) {
                 if ($show_details) {
                     print " Inserting {$strip['title']} ({$image_url}) Dated: {$time}\n";
                 }
                 $title = i($strip, 'title');
                 if (is_array($title)) {
                     $title = implode('', $title);
                 }
                 if (!isset($strip['link'])) {
                     $strip['link'] = '';
                 }
                 if (!$title) {
                     $title = 'Comic for ' . date('jS M, Y', strtotime($time));
                 }
                 $sql->execQuery("UPDATE Comic SET latest_comic_fetched_on='{$time}' WHERE id={$feed['id']} AND '{$time}'>latest_comic_fetched_on");
                 //Yes, its not normalized - I know. Now shut up
                 $sql->execQuery("INSERT INTO Strip(name, image_url, url, contents, guid, added_on, comic_id) " . " VALUES('" . $sql->escape($title) . "'," . "'" . $sql->escape($image_url) . "'," . "'" . $sql->escape($strip['link']) . "'," . "'" . $sql->escape($contents) . "'," . "'" . $sql->escape($strip['guid']) . "','{$time}','{$feed['id']}')");
                 $image_url_of_latest_strips[] = $image_url;
                 if ($strip['guid']) {
                     $guids_of_latest_strips[] = $strip['guid'];
                 }
             } else {
                 if ($show_details) {
                     print "Done\n";
                 }
                 continue 2;
                 // We already have this comic - so we must have the stuff that came before it. So skip to te next comic - not just the next strip.
             }
         }
     }
 }
/**
 * See http://www.bin-co.com/php/scripts/load/
 * Version : 2.00.A
 */
function load($url, $options = array())
{
    $default_options = array('method' => 'get', 'return_info' => false, 'return_body' => true, 'cache' => false, 'referer' => '', 'headers' => array(), 'session' => false, 'session_close' => false);
    // Sets the default options.
    foreach ($default_options as $opt => $value) {
        if (!isset($options[$opt])) {
            $options[$opt] = $value;
        }
    }
    $url_parts = parse_url($url);
    $ch = false;
    $info = array('http_code' => 200);
    $response = '';
    $send_header = array('Accept' => 'text/*', 'User-Agent' => 'BinGet/1.00.A (http://www.bin-co.com/php/scripts/load/)') + $options['headers'];
    // Add custom headers provided by the user.
    if ($options['cache']) {
        $cache_folder = '/tmp/php-load-function/';
        if (isset($options['cache_folder'])) {
            $cache_folder = $options['cache_folder'];
        }
        if (!file_exists($cache_folder)) {
            $old_umask = umask(0);
            // Or the folder will not get write permission for everybody.
            mkdir($cache_folder, 0777);
            umask($old_umask);
        }
        $cache_file_name = md5($url) . '.cache';
        $cache_file = joinPath($cache_folder, $cache_file_name);
        //Don't change the variable name - used at the end of the function.
        if (file_exists($cache_file)) {
            // Cached file exists - return that.
            $response = file_get_contents($cache_file);
            //Seperate header and content
            $separator_position = strpos($response, "\r\n\r\n");
            $header_text = substr($response, 0, $separator_position);
            $body = substr($response, $separator_position + 4);
            foreach (explode("\n", $header_text) as $line) {
                $parts = explode(": ", $line);
                if (count($parts) == 2) {
                    $headers[$parts[0]] = chop($parts[1]);
                }
            }
            $headers['cached'] = true;
            if (!$options['return_info']) {
                return $body;
            } else {
                return array('headers' => $headers, 'body' => $body, 'info' => array('cached' => true));
            }
        }
    }
    ///////////////////////////// Curl /////////////////////////////////////
    //If curl is available, use curl to get the data.
    if (function_exists("curl_init") and !(isset($options['use']) and $options['use'] == 'fsocketopen')) {
        //Don't use curl if it is specifically stated to use fsocketopen in the options
        if (isset($options['post_data'])) {
            //There is an option to specify some data to be posted.
            $page = $url;
            $options['method'] = 'post';
            if (is_array($options['post_data'])) {
                //The data is in array format.
                $post_data = array();
                foreach ($options['post_data'] as $key => $value) {
                    $post_data[] = "{$key}=" . urlencode($value);
                }
                $url_parts['query'] = implode('&', $post_data);
            } else {
                //Its a string
                $url_parts['query'] = $options['post_data'];
            }
        } else {
            if (isset($options['method']) and $options['method'] == 'post') {
                $page = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];
            } else {
                $page = $url;
            }
        }
        if ($options['session'] and isset($GLOBALS['_binget_curl_session'])) {
            $ch = $GLOBALS['_binget_curl_session'];
        } else {
            $ch = curl_init($url_parts['host']);
        }
        curl_setopt($ch, CURLOPT_URL, $page) or die("Invalid cURL Handle Resouce");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //Just return the data - not print the whole thing.
        curl_setopt($ch, CURLOPT_HEADER, true);
        //We need the headers
        curl_setopt($ch, CURLOPT_NOBODY, !$options['return_body']);
        //The content - if true, will not download the contents. There is a ! operation - don't remove it.
        if (isset($options['method']) and $options['method'] == 'post' and isset($url_parts['query'])) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $url_parts['query']);
        }
        //Set the headers our spiders sends
        curl_setopt($ch, CURLOPT_USERAGENT, $send_header['User-Agent']);
        //The Name of the UserAgent we will be using ;)
        $custom_headers = array("Accept: " . $send_header['Accept']);
        if (isset($options['modified_since'])) {
            array_push($custom_headers, "If-Modified-Since: " . gmdate('D, d M Y H:i:s \\G\\M\\T', strtotime($options['modified_since'])));
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $custom_headers);
        if ($options['referer']) {
            curl_setopt($ch, CURLOPT_REFERER, $options['referer']);
        }
        curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/binget-cookie.txt");
        //If ever needed...
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        if (isset($url_parts['user']) and isset($url_parts['pass'])) {
            $custom_headers = array("Authorization: Basic " . base64_encode($url_parts['user'] . ':' . $url_parts['pass']));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $custom_headers);
        }
        $response = curl_exec($ch);
        $info = curl_getinfo($ch);
        //Some information on the fetch
        if ($options['session'] and !$options['session_close']) {
            $GLOBALS['_binget_curl_session'] = $ch;
        } else {
            curl_close($ch);
        }
        //If the session option is not set, close the session.
        //////////////////////////////////////////// FSockOpen //////////////////////////////
    } else {
        //If there is no curl, use fsocketopen - but keep in mind that most advanced features will be lost with this approch.
        if (isset($url_parts['query'])) {
            if (isset($options['method']) and $options['method'] == 'post') {
                $page = $url_parts['path'];
            } else {
                $page = $url_parts['path'] . '?' . $url_parts['query'];
            }
        } else {
            $page = $url_parts['path'];
        }
        if (!isset($url_parts['port'])) {
            $url_parts['port'] = 80;
        }
        $fp = fsockopen($url_parts['host'], $url_parts['port'], $errno, $errstr, 30);
        if ($fp) {
            $out = '';
            if (isset($options['method']) and $options['method'] == 'post' and isset($url_parts['query'])) {
                $out .= "POST {$page} HTTP/1.1\r\n";
            } else {
                $out .= "GET {$page} HTTP/1.0\r\n";
                //HTTP/1.0 is much easier to handle than HTTP/1.1
            }
            $out .= "Host: {$url_parts['host']}\r\n";
            $out .= "Accept: {$send_header['Accept']}\r\n";
            $out .= "User-Agent: {$send_header['User-Agent']}\r\n";
            if (isset($options['modified_since'])) {
                $out .= "If-Modified-Since: " . gmdate('D, d M Y H:i:s \\G\\M\\T', strtotime($options['modified_since'])) . "\r\n";
            }
            $out .= "Connection: Close\r\n";
            //HTTP Basic Authorization support
            if (isset($url_parts['user']) and isset($url_parts['pass'])) {
                $out .= "Authorization: Basic " . base64_encode($url_parts['user'] . ':' . $url_parts['pass']) . "\r\n";
            }
            //If the request is post - pass the data in a special way.
            if (isset($options['method']) and $options['method'] == 'post' and $url_parts['query']) {
                $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
                $out .= 'Content-Length: ' . strlen($url_parts['query']) . "\r\n";
                $out .= "\r\n" . $url_parts['query'];
            }
            $out .= "\r\n";
            fwrite($fp, $out);
            while (!feof($fp)) {
                $response .= fgets($fp, 128);
            }
            fclose($fp);
        }
    }
    //Get the headers in an associative array
    $headers = array();
    if ($info['http_code'] == 404) {
        $body = "";
        $headers['Status'] = 404;
    } else {
        //Seperate header and content
        $header_text = substr($response, 0, $info['header_size']);
        $body = substr($response, $info['header_size']);
        foreach (explode("\n", $header_text) as $line) {
            $parts = explode(": ", $line);
            if (count($parts) == 2) {
                $headers[$parts[0]] = chop($parts[1]);
            }
        }
    }
    if (isset($cache_file)) {
        //Should we cache the URL?
        file_put_contents($cache_file, $response);
    }
    if ($options['return_info']) {
        return array('headers' => $headers, 'body' => $body, 'info' => $info, 'curl_handle' => $ch);
    }
    return $body;
}
<?php

/**
 * File defines the ArticleListController PageController class
 * @package PageController
 */
/**
 */
$current_dir = dirname(__FILE__);
require_once $current_dir . DIRECTORY_SEPARATOR . "shared" . DIRECTORY_SEPARATOR . "bootstrap.php";
require_once joinPath(INCLUDES_DIR, "models", "Article.php");
require_once joinPath(INCLUDES_DIR, "models", "ArticleTag.php");
/**
 * Display published article list
 *
 * Read in list of the latest published articles.
 * Display results in the page.
 * @package PageController
 */
class ArticleListController implements Controller
{
    /**
     * PageTemplate object used to render page
     * @access protected
     * @var PageTemplate
     */
    protected $template;
    /**
     * Constructor. Create instance of PageTemplate using default index_tpl.php file
     * @access public
     */
 /**
  * Run method with main page logic
  * 
  * Populate template and Display form for editing an event entry. For POST requests,
  * check user credentials, check if event exists and then update entry in database.
  * Available to admins only
  * @access public
  */
 public function run()
 {
     $session = Session::getInstance();
     $user = $session->getUser();
     //if (!$user || !$user->isAdmin ()) {
     if (!$user || !$user->validUser()) {
         $session->setMessage("Do not have permission to access", Session::MESSAGE_ERROR);
         header("Location: " . BASE_URL);
         return;
     }
     $form_errors = array();
     $form_values = array("id" => "", "title" => "", "description" => "", "sanctioned" => "", "status" => "", "date" => "", "platform" => "");
     $eventDAO = EventDAO::getInstance();
     $event = null;
     if (!empty($_POST)) {
         $form_values["id"] = isset($_POST["id"]) && is_numeric($_POST["id"]) ? intval($_POST["id"]) : "";
         $form_values["title"] = isset($_POST["title"]) ? trim($_POST["title"]) : "";
         $form_values["description"] = isset($_POST["description"]) ? trim($_POST["description"]) : "";
         $form_values["platform"] = isset($_POST["platform"]) ? trim($_POST["platform"]) : "";
         $form_values["sanctioned"] = isset($_POST["sanctioned"]) ? trim($_POST["sanctioned"]) : "";
         $form_values["status"] = isset($_POST["status"]) ? trim($_POST["status"]) : "";
         $form_values["date"] = isset($_POST["date"]) ? trim($_POST["date"]) : "";
         if (empty($form_values["id"])) {
             $form_errors["id"] = "No id specified";
         }
         if (empty($form_values["title"])) {
             $form_errors["title"] = "No title specified";
         }
         if (empty($form_values["description"])) {
             $form_errors["description"] = "No description specified";
         }
         if (empty($form_values["platform"])) {
             $form_errors["platform"] = "No platform specified";
         } else {
             if (!is_numeric($form_values["platform"])) {
                 $form_errors["platform"] = "Platform choice must be an integer value";
             } else {
                 $platformDAO = PlatformDAO::getInstance();
                 $platform = $platformDAO->load($form_values["platform"]);
                 if (!$platform) {
                     $form_errors["platform"] = "Invalid platform specified";
                 }
             }
         }
         if ($user->isAdmin() && empty($form_values["sanctioned"])) {
             $form_errors["sanctioned"] = "No sanctioned flag specified";
         } else {
             if ($user->isAdmin() && strcmp($form_values["sanctioned"], "true") != 0 && strcmp($form_values["sanctioned"], "false") != 0) {
                 $form_errors["sanctioned"] = "sanctioned flag must be a boolean value";
             }
         }
         if ($user->isAdmin() && empty($form_values["status"])) {
             $form_errors["status"] = "No status flag specified";
         } else {
             if ($user->isAdmin() && !is_numeric($form_values["status"])) {
                 $form_errors["status"] = "Status flag must be an integer value";
             } else {
                 if ($user->isAdmin()) {
                     $status = intval($form_values["status"]);
                     $tmp = new Event();
                     try {
                         $tmp->setStatus($status);
                     } catch (Exception $e) {
                         $form_errors["status"] = "Invalid value for status";
                     }
                 }
             }
         }
         if (empty($form_values["date"])) {
             $form_errors["date"] = "No date specified";
         } else {
             if (strtotime($_POST["date"]) == 0) {
                 $form_errors["date"] = "An invalid date was specified";
                 $form_values["date"] = "";
             }
         }
         if (empty($form_errors)) {
             $event = $eventDAO->load($form_values["id"]);
             if ($event && ($user->isAdmin() || $event->getUserId() == $user->getId())) {
                 $event->setTitle($form_values["title"]);
                 $event->setDescription($form_values["description"]);
                 $event->setPlatformId(intval($form_values["platform"]));
                 if ($user->isAdmin() || $user->validUser() && $user->getUserType() == User::TRUSTED_TYPE) {
                     $sanctioned_value = strcmp($form_values["sanctioned"], "true") == 0 ? true : false;
                     $event->setSanctioned($sanctioned_value);
                     $event->setStatus($form_values["status"]);
                 }
                 $pubtimestamp = strtotime($_POST["date"]);
                 $event->setDate($pubtimestamp);
                 $event->setUserId($user->id);
                 //print_r ($event);
                 if ($eventDAO->save($event)) {
                     // Attempt to ignore for regular admin edits
                     if ($event->getUserId() == $user->getId()) {
                         require_once joinPath(INCLUDES_DIR, "models", "Attendance.php");
                         Attendance::emailAttendees($event, $user);
                     }
                     $session->setMessage("Event details saved");
                     header("Location: edit_event.php?id={$event->getId()}");
                     return;
                 } else {
                     $session->setMessage("Event details could not be saved", Session::MESSAGE_ERROR);
                 }
             }
         } else {
             if (empty($form_errors["id"])) {
                 $event = $eventDAO->load($form_values["id"]);
             }
         }
     } else {
         if (!empty($_GET)) {
             $form_values["id"] = isset($_GET["id"]) ? $_GET["id"] : "";
             if (empty($form_values["id"])) {
                 header("Location: " . BASE_URL);
                 return;
             } else {
                 $event = $eventDAO->load($form_values["id"]);
                 // Event does not exist. Pass null to template
                 if (!$event) {
                 } else {
                     if (!$user->isAdmin() && $event->userId != $user->id) {
                         $session->setMessage("Do not have permission to edit page", Session::MESSAGE_ERROR);
                         header("Location: " . BASE_URL);
                         return;
                     } else {
                         $form_values["id"] = $event->getId();
                         $form_values["title"] = $event->getTitle();
                         $form_values["description"] = $event->getDescription();
                         $form_values["sanctioned"] = $event->getSanctioned() == true ? "true" : "false";
                         $form_values["status"] = $event->getStatus();
                         $form_values["date"] = strftime("%d %B %Y", $event->getDate());
                         $form_values["platform"] = $event->getPlatformId();
                     }
                 }
             }
         }
     }
     $platformDAO = PlatformDAO::getInstance();
     $platform_array = $platformDAO->all();
     $this->template->render(array("title" => "Edit Event", "extra_header" => joinPath("headers", "jscal_header_tpl.php"), "main_page" => "edit_event_tpl.php", "session" => $session, "event" => $event, "form_values" => $form_values, "form_errors" => $form_errors, "platform_array" => $platform_array));
 }
Exemple #26
0
}
/**
 * The current mode of the system. This will affect how errors will be shown
 *  d = Development Mode
 *	t = Testing Mode
 *	p = Production Mode
 */
if (!isset($config['mode'])) {
    $config['mode'] = 'd';
}
//Default Config Mode
if ($config['mode'] == 'd') {
    error_reporting(E_ALL);
    $Logger = false;
    if (i($QUERY, 'debug') == 'log') {
        include joinPath("Development", "Logger.php");
        $Logger = new Logger();
        $Logger->log("\nRendering Request: {$_SERVER['REQUEST_URI']}");
    }
} elseif ($config['mode'] == 'p') {
    error_reporting(0);
}
// Database connection is optional
$sql = false;
if (isset($config['db_host']) and $config['db_host']) {
    $sql = new Sql($config['db_host'], $config['db_user'], $config['db_password'], $config['db_database']);
    // Connect to DB
    Sql::$mode = $config['mode'];
}
if (!isset($config['use_mvc']) or $config['use_mvc'] === false) {
    $template = new MVC();
Exemple #27
0
 /**
  * Prints the page portion. This is done by including 'page.php' inside the 'layout' folder.
  */
 function printLayout()
 {
     extract($GLOBALS);
     $title = $this->title ? $this->title : $config['site_title'];
     $includes = implode($this->includes, "\n");
     include joinPath($config['site_folder'], $this->options['template_folder'], "/layout/", $this->layout);
 }
<?php

/**
 * File defines the class Session which will contain data about
 * the current user
 * @package UGA
 */
/**
 *
 */
if (!defined("IN_APP")) {
    exit;
}
require_once joinPath("models", "User.php");
/**
 * Session management class
 *
 * Class contains reference to the current user of a session
 * and other miscellaneous data related to a session
 * @package UGA
 */
class Session
{
    /**
     * Message normal status flag
     * @access public
     * @var int
     */
    const MESSAGE_NORMAL = 1;
    /**
     * Message error status flag
<?php

/**
 * File defines the LoginController PageController class
 * @package PageController
 */
/**
 */
$current_dir = dirname(__FILE__);
require_once $current_dir . DIRECTORY_SEPARATOR . "shared" . DIRECTORY_SEPARATOR . "bootstrap.php";
require_once joinPath(INCLUDES_DIR, "models", "User.php");
require_once joinPath(INCLUDES_DIR, "Session.php");
/**
 * Login form page and login validation page
 *
 * Display form for entering login data. For POST requests,
 * check if a user exists with the specified password, and enter user id into session if login is valid.
 * @package PageController
 */
class LoginController implements Controller
{
    /**
     * PageTemplate object used to render page
     * @access protected
     * @var PageTemplate
     */
    protected $template;
    /**
     * Constructor. Create instance of PageTemplate using default index_tpl.php file
     * @access public
     */
Exemple #30
0
 /**
  * Prints the page portion. This is done by including 'page.php' inside the 'layout' folder.
  */
 function printLayout()
 {
     extract($GLOBALS);
     $title = $this->title ? $this->title : $config['site_title'];
     $includes = implode($this->includes, "\n");
     $css_includes = implode($this->css_includes, "\n");
     $js_includes = implode($this->js_includes, "\n");
     include joinPath($config['site_folder'], $this->options['layout_file']);
 }