public function get_templates($path = false, $include_hidden = false, $initial_path = false)
 {
     $Perch = Perch::fetch();
     if ($path === false) {
         $path = PERCH_TEMPLATE_PATH . '/categories';
     }
     if ($initial_path === false) {
         $initial_path = $path;
     }
     $a = array();
     if (is_dir($path)) {
         if ($dh = opendir($path)) {
             while (($file = readdir($dh)) !== false) {
                 if (substr($file, 0, 1) != '.' && ($include_hidden || substr($file, 0, 1) != '_') && !preg_match($Perch->ignore_pattern, $file)) {
                     $extension = PerchUtil::file_extension($file);
                     if ($extension == 'html' || $extension == 'htm') {
                         $p = str_replace($initial_path, '', $path);
                         if (!$p) {
                             $a[PerchLang::get('Categories')][] = array('filename' => $file, 'path' => $file, 'label' => $this->template_display_name($file));
                         } else {
                             $a[] = array('filename' => $file, 'path' => ltrim($p, '/') . '/' . $file, 'label' => $this->template_display_name($file));
                         }
                     } else {
                         $a[$this->template_display_name($file)] = $this->get_templates($path . '/' . $file, $include_hidden, $initial_path);
                     }
                 }
             }
             closedir($dh);
         }
         if (PerchUtil::count($a)) {
             $a = PerchUtil::array_sort($a, 'label');
         }
     }
     return $a;
 }
 function __construct($file = false, $namespace = 'content', $relative_path = true)
 {
     $Perch = Perch::fetch();
     // required to define constants
     if ($file && substr($file, -5) !== '.html') {
         $file .= '.html';
     }
     $this->current_file = $file;
     $this->namespace = $namespace;
     if ($file && $relative_path) {
         $file = PerchUtil::file_path(PERCH_TEMPLATE_PATH . '/' . $file);
     }
     if ($file != false && file_exists($file)) {
         $this->file = $file;
         $this->template = $file;
         PerchUtil::debug('Using template: ' . str_replace(PERCH_PATH, '', $file), 'template');
         $this->status = 200;
         $this->file_path = pathinfo($file, PATHINFO_DIRNAME);
     } else {
         if ($file != false) {
             PerchUtil::debug('Template file not found: ' . $file, 'template-error');
         }
         $this->status = 404;
     }
     // Mock up fallback functions if server doesn't have mbstring
     $this->mb_fallback();
 }
function perch_forms_form_handler($SubmittedForm)
{
    if ($SubmittedForm->validate()) {
        $API = new PerchAPI(1.0, 'perch_forms');
        $Forms = new PerchForms_Forms($API);
        $formKey = $SubmittedForm->id;
        $Form = $Forms->find_by_key($formKey);
        if (!is_object($Form)) {
            $data = array();
            $data['formKey'] = $formKey;
            $data['formTemplate'] = $SubmittedForm->templatePath;
            $data['formOptions'] = PerchUtil::json_safe_encode(array('store' => true));
            $attrs = $SubmittedForm->get_form_attributes();
            if ($attrs->label()) {
                $data['formTitle'] = $attrs->label();
            } else {
                $data['formTitle'] = PerchUtil::filename($formKey, false);
            }
            $Form = $Forms->create($data);
        }
        if (is_object($Form)) {
            $Form->process_response($SubmittedForm);
        }
    }
    $Perch = Perch::fetch();
    PerchUtil::debug($Perch->get_form_errors($SubmittedForm->formID));
}
Example #4
0
 public static function fetch()
 {
     if (!isset(self::$instance)) {
         $c = __CLASS__;
         self::$instance = new $c();
     }
     return self::$instance;
 }
 public function add_page_resources()
 {
     $Perch = Perch::fetch();
     $Perch->add_css(PERCH_LOGINPATH . $this->_location . '/css/simona_table_admin.css');
     $Perch->add_css(PERCH_LOGINPATH . $this->_location . $this->_handsontable_location . 'handsontable.full.min.css');
     $Perch->add_javascript(PERCH_LOGINPATH . $this->_location . $this->_handsontable_location . 'handsontable.full.min.js');
     $Perch->add_javascript(PERCH_LOGINPATH . $this->_location . '/js/simona_table_admin.js');
 }
 public function __construct()
 {
     $dropbox_config = PerchConfig::get('dropbox');
     $Perch = Perch::fetch();
     $this->Client = new dbx\Client($dropbox_config['access_token'], "Perch Runway/" . $Perch->version);
     $conf = PerchConfig::get('env');
     $this->temp_folder = $conf['temp_folder'];
 }
 public function add_page_resources()
 {
     //this function seems to be called twice for some reason (Perch Runway)?
     $Perch = Perch::fetch();
     $Perch->add_css($this->_chessboardjs_location . 'css/chessboard-0.3.0.min.css');
     $Perch->add_css($this->_location . 'css/simona_chessboard_admin.css');
     $Perch->add_javascript($this->_chessboardjs_location . 'js/chessboard-0.3.0.min.js');
     $Perch->add_javascript($this->_location . 'js/simona_chessboard_admin.js');
 }
Example #8
0
function perch_blog_form_handler($SubmittedForm)
{
    if ($SubmittedForm->formID == 'comment' && $SubmittedForm->validate()) {
        $API = new PerchAPI(1.0, 'perch_blog');
        $Comments = new PerchBlog_Comments($API);
        $Comments->receive_new_comment($SubmittedForm);
    }
    $Perch = Perch::fetch();
    PerchUtil::debug($Perch->get_form_errors($SubmittedForm->formID));
}
Example #9
0
function listing_form_handler($SubmittedForm)
{
    if ($SubmittedForm->formID == 'listing' && $SubmittedForm->validate()) {
        $API = new PerchAPI(1.0, 'listing');
        $Listings = new Listings($API);
        $Listings->receive_new_listing($SubmittedForm);
    }
    $Perch = Perch::fetch();
    PerchUtil::debug($Perch->get_form_errors($SubmittedForm->formID));
}
Example #10
0
function perch_mailchimp_form_handler($SubmittedForm)
{
    if ($SubmittedForm->validate()) {
        $API = new PerchAPI(1.0, 'perch_mailchimp');
        $Subscribers = new PerchMailChimp_Subscribers($API);
        $Subscribers->subscribe_from_form($SubmittedForm);
    }
    $Perch = Perch::fetch();
    PerchUtil::debug($Perch->get_form_errors($SubmittedForm->formID));
}
 public function path($bucket = false)
 {
     $file = $this->details['versionPath'];
     if ($bucket === false) {
         $bucket_name = $this->details['imageBucket'];
         $Perch = Perch::fetch();
         $bucket = $Perch->get_resource_bucket($bucket_name);
     }
     return $bucket['web_path'] . '/' . $file;
 }
 public function add_page_resources()
 {
     //this function seems to be called twice for some reason (Perch Runway)?
     $Perch = Perch::fetch();
     $Perch->add_css($this->_location . 'css/simona_piechart_admin.css');
     $Perch->add_css($this->_handsontable_location . 'handsontable.full.min.css');
     $Perch->add_javascript('https://www.google.com/jsapi');
     $Perch->add_javascript($this->_handsontable_location . 'handsontable.full.min.js');
     $Perch->add_javascript($this->_location . 'js/spin.min.js');
     $Perch->add_javascript($this->_location . 'js/simona_piechart_admin.js');
 }
 public function delete()
 {
     if ($this->clean_resources && !$this->resourceInLibrary()) {
         $Perch = Perch::fetch();
         $bucket = $Perch->get_resource_bucket($this->resourceBucket());
         $file_path = PerchUtil::file_path($bucket['file_path'] . '/' . $this->resourceFile());
         if (file_exists($file_path) && !is_dir($file_path)) {
             unlink($file_path);
             PerchUtil::debug('Deleting resource: ' . $file_path);
         }
     }
     return parent::delete();
 }
 public function create($data)
 {
     if (!isset($data['catDisplayPath'])) {
         $data['catDisplayPath'] = '';
     }
     $Category = parent::create($data);
     if (is_object($Category)) {
         $Perch = Perch::fetch();
         $Perch->event($this->event_prefix . '.create', $Category);
         $Category->update_tree_position();
     }
     return $Category;
 }
 public function set_from_string($str_template, $namespace)
 {
     $Perch = Perch::fetch();
     // called to make sure constants are defined.
     $this->namespace = $namespace;
     $this->Template = new PerchTemplate(false, $namespace, $relative_path = false);
     $this->Template->set_template('__STRING__');
     $this->Template->load($str_template);
     $this->Template->enable_encoding();
     $this->Template->apply_post_processing = true;
     $this->file = $this->Template->file;
     return $this->Template->status;
 }
 function __construct($version = 1.0, $app_id, $Lang)
 {
     $this->app_id = $app_id;
     $this->version = $version;
     $this->Lang = $Lang;
     $this->orig_post = $_POST;
     // Include editor plugin
     $dir = PERCH_PATH . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'editors' . DIRECTORY_SEPARATOR . PERCH_APPS_EDITOR_PLUGIN;
     if (is_dir($dir) && is_file($dir . DIRECTORY_SEPARATOR . '_config.inc')) {
         $Perch = Perch::fetch();
         $Perch->add_head_content(str_replace('PERCH_LOGINPATH', PERCH_LOGINPATH, file_get_contents($dir . DIRECTORY_SEPARATOR . '_config.inc')));
     }
     parent::__construct($app_id);
 }
 public function __construct($args)
 {
     if (PerchUtil::count($args)) {
         $this->event = array_shift($args);
         $this->subject = array_shift($args);
         $this->args = $args;
         $Perch = Perch::fetch();
         if ($Perch->admin) {
             $Users = new PerchUsers();
             $this->user = $Users->get_current_user();
         } else {
             $this->runtime = true;
         }
     }
 }
function perch_find_posted_forms()
{
    if (isset($_POST['cms-form']) && $_POST['cms-form'] != '') {
        $Perch = Perch::fetch();
        $post = $_POST;
        $key = $post['cms-form'];
        unset($post['cms-form']);
        $Perch->dispatch_form($key, $post, $_FILES);
    }
    if (isset($_GET['cms-form']) && $_GET['cms-form'] != '') {
        $Perch = Perch::fetch();
        $post = $_GET;
        $key = $post['cms-form'];
        unset($post['cms-form']);
        $Perch->dispatch_form($key, $post, $_FILES);
    }
}
 /**
  * Get an array of templates in the content folder.
  *
  * @param string $path 
  * @return void
  * @author Drew McLellan
  */
 public function get_templates($path = false, $include_hidden = false, $initial_path = false)
 {
     $Perch = Perch::fetch();
     if ($path === false) {
         $path = PERCH_TEMPLATE_PATH . '/forms/emails';
     }
     if ($initial_path === false) {
         $initial_path = $path;
     }
     $a = array();
     $groups = array();
     $p = false;
     if (is_dir($path)) {
         if ($dh = opendir($path)) {
             while (($file = readdir($dh)) !== false) {
                 if (substr($file, 0, 1) != '.' && ($include_hidden || substr($file, 0, 1) != '_') && !preg_match($Perch->ignore_pattern, $file)) {
                     $extension = PerchUtil::file_extension($file);
                     if ($extension == 'html' || $extension == 'htm') {
                         $p = str_replace($initial_path, '', $path);
                         if (!$p) {
                             $a[PerchLang::get('Templates')][] = array('filename' => $file, 'value' => $file, 'path' => $file, 'label' => $this->template_display_name($file));
                         } else {
                             $a[] = array('filename' => $file, 'value' => ltrim($p, '/') . '/' . $file, 'path' => ltrim($p, '/') . '/' . $file, 'label' => $this->template_display_name($file));
                         }
                     } else {
                         // Use this one of infinite recursive nesting. Group stuff below normalised for HTML select optgroups that only do one level
                         //$a[$this->template_display_name($file)] = $this->get_templates($path.'/'.$file, $include_hidden, $initial_path);
                         if ($p) {
                             $group_name = $this->template_display_name(trim($p, '/\\') . '/' . $file);
                         } else {
                             $group_name = $this->template_display_name($file);
                         }
                         $groups[$group_name] = $this->get_templates($path . '/' . $file, $include_hidden, $initial_path);
                     }
                 }
             }
             closedir($dh);
         }
         if (PerchUtil::count($a)) {
             $a = PerchUtil::array_sort($a, 'label');
         }
     }
     return $a + $groups;
 }
Example #20
0
 public function __construct()
 {
     parent::__construct();
     if (!defined('PERCH_STRONG_PASSWORDS')) {
         define('PERCH_STRONG_PASSWORDS', PERCH_PARANOID);
     }
     if (!defined('PERCH_PASSWORD_MIN_LENGTH')) {
         define('PERCH_PASSWORD_MIN_LENGTH', 6);
     }
     if (!defined('PERCH_MAX_FAILED_LOGINS')) {
         define('PERCH_MAX_FAILED_LOGINS', 10);
     }
     if (!defined('PERCH_AUTH_LOCKOUT_DURATION')) {
         define('PERCH_AUTH_LOCKOUT_DURATION', '1 HOUR');
     }
     if (!defined('PERCH_VERIFY_UPLOADS')) {
         define('PERCH_VERIFY_UPLOADS', PERCH_PARANOID);
     }
 }
 public function update_meta($fire_events = true)
 {
     $data = array();
     if ($this->catParentID() !== '0' && $this->catParentID() !== 'null') {
         $Categories = new PerchCategories_Categories();
         $ParentCat = $Categories->find($this->catParentID());
         $data['catPath'] = $ParentCat->catPath() . $this->catSlug() . '/';
         $data['catTreePosition'] = $ParentCat->catTreePosition() . '-' . str_pad($this->catOrder(), 3, '0', STR_PAD_LEFT);
     } else {
         $Sets = new PerchCategories_Sets();
         $Set = $Sets->find($this->setID());
         $data['catPath'] = $Set->setSlug() . '/' . $this->catSlug() . '/';
         $data['catTreePosition'] = str_pad($this->setID(), 3, '0', STR_PAD_LEFT) . '-' . str_pad($this->catOrder(), 3, '0', STR_PAD_LEFT);
     }
     $data['catDisplayPath'] = $this->get_display_path();
     if (count($data)) {
         parent::update($data);
         if ($fire_events) {
             $Perch = Perch::fetch();
             $Perch->event($this->event_prefix . '.update', $this);
         }
     }
 }
 public static function subnav($CurrentUser, $pages, $Lang = false)
 {
     $s = '';
     if (PerchUtil::count($pages)) {
         $Perch = Perch::fetch();
         $section = $Perch->get_nav_page();
         $prefix = '';
         if (strpos($section, 'addons') !== false) {
             $parts = explode('/', $section);
             while (count($parts) && array_shift($parts) != 'apps') {
             }
             $prefix .= 'addons/apps/';
             $section = implode('/', $parts);
         }
         $s .= '<ul class="subnav">';
         foreach ($pages as $page) {
             // Runway?
             if (isset($page['runway']) && $page['runway'] == true && !PERCH_RUNWAY) {
                 continue;
             }
             if (isset($page['priv']) && $CurrentUser->has_priv($page['priv']) || !isset($page['priv'])) {
                 if (is_array($page['page'])) {
                     $paths = $page['page'];
                 } else {
                     $paths = explode(',', $page['page']);
                 }
                 if ($Lang === false) {
                     $label = PerchLang::get($page['label']);
                 } else {
                     $label = $Lang->get($page['label']);
                 }
                 $s .= '<li' . (in_array($section, $paths) ? ' class="selected"' : '') . '><a href="' . PerchUtil::html(PERCH_LOGINPATH . '/' . $prefix . $paths[0] . (strpos($paths[0], '?') ? '' : '/')) . '">' . $label . '</a>';
                 if (isset($page['badge']) && $page['badge'] != '') {
                     $s .= '<span class="badge">' . PerchUtil::html($page['badge']) . '</span>';
                 }
                 $s .= '</li>';
             }
         }
         $s .= '</ul>';
     }
     return $s;
 }
Example #23
0
    <h1>Installing...</h1>

<?php 
if (defined('PERCH_DB_PREFIX')) {
    echo '<ul class="importables">';
    if (isset($_GET['auto'])) {
        echo '<li class="success icon">Your config file was written automatically.</li>';
    }
    $db = PerchDB::fetch();
    $Perch = Perch::fetch();
    $sql = file_get_contents('database.sql');
    $sql = str_replace('__PREFIX__', PERCH_DB_PREFIX, $sql);
    $sql = str_replace('__PERCH_LOGINPATH__', PERCH_LOGINPATH, $sql);
    $sql = str_replace('__PERCH_VERSION__', $Perch->version, $sql);
    $queries = explode(';', $sql);
    $msgs = array();
    if (PerchUtil::count($queries) > 0) {
        foreach ($queries as $query) {
            $query = trim($query);
            if ($query != '') {
                if (!$db->execute($query)) {
                    if ($db->error_msg != '') {
                        $msgs[] = $db->error_msg;
                        $db->error_msg = false;
                    }
                }
            }
        }
        // test that it worked
        $tables = $db->get_rows('SHOW TABLES');
        $db_fail = true;
Example #24
0
 public function resize_image($image_path, $target_w = false, $target_h = false, $crop = false, $suffix = false)
 {
     $Perch = Perch::fetch();
     $bail = false;
     if ($this->mode === false) {
         return false;
     }
     if ($crop) {
         PerchUtil::debug('Resizing and cropping image... (' . $this->mode . ', ' . sprintf('w%d h%d @%dx %s', $target_w, $target_h, $this->density, $suffix) . ')');
     } else {
         PerchUtil::debug('Resizing image... (' . $this->mode . ', ' . sprintf('w%d h%d @%dx %s', $target_w, $target_h, $this->density, $suffix) . ')');
     }
     $info = getimagesize($image_path);
     // WebP?
     if (!is_array($info)) {
         if ($this->is_webp($image_path)) {
             $info = $this->get_webp_size($image_path);
         }
     }
     // SVG?
     $svg = false;
     if (!is_array($info)) {
         // $svg gets populated with the mime type if it's an SVG
         $svg = $this->is_svg($image_path);
         if ($svg) {
             $info = $this->get_svg_size($image_path);
             // Can't crop SVG
             $crop = false;
         }
     }
     if (!is_array($info)) {
         return false;
     }
     if ($svg) {
         // Only need one SVG file for all sizes.
         $save_as = $image_path;
     } else {
         $save_as = $this->get_resized_filename($image_path, $target_w, $target_h, $suffix, $this->density);
     }
     $image_w = $info[0];
     $image_h = $info[1];
     $crop_x = 0;
     $crop_y = 0;
     $crop_w = 0;
     $crop_h = 0;
     $image_ratio = $image_w / $image_h;
     if ($svg) {
         // Constrain by width
         if ($target_w) {
             $new_w = $target_w;
             $new_h = $target_w / $image_ratio;
         }
         // Constrain by height
         if ($target_h) {
             $new_h = $target_h;
             $new_w = $target_h * $image_ratio;
         }
     } else {
         // Constrain by width
         if ($target_w && $image_w >= $target_w) {
             $new_w = $target_w;
             $new_h = $target_w / $image_ratio;
         }
         // Constrain by height
         if ($target_h && $image_h >= $target_h) {
             $new_h = $target_h;
             $new_w = $target_h * $image_ratio;
         }
     }
     // Both specified, and crop set
     if ($target_w && $target_h && $crop) {
         $crop_w = $target_w;
         $crop_h = $target_h;
         $crop_ratio = $crop_w / $crop_h;
         if ($image_ratio >= $crop_ratio) {
             // Landscape or square crop
             $new_h = (int) $target_h;
             $new_w = $target_h * $image_ratio;
             $crop_y = 0;
             $crop_x = $new_w / 2 - $target_w / 2;
         }
         if ($crop_ratio > $image_ratio) {
             // Portrait crop
             $new_w = (int) $target_w;
             $new_h = $target_w / $image_ratio;
             $crop_x = 0;
             $crop_y = $new_h / 2 - $target_h / 2;
         }
         // Check we're not cropping upwardly
         if ($crop_w > $image_w || $crop_h > $image_h) {
             $crop_x = 0;
             $crop_y = 0;
             $crop_w = 0;
             $crop_h = 0;
             $crop = false;
         }
         //PerchUtil::debug("Crop info: $crop_x, $crop_y, $crop_w, $crop_h");
     }
     if ($target_w && $target_h && !$crop) {
         // Normal resize
         if ($this->box_constrain) {
             if ($image_w / $target_w > $image_h / $target_h) {
                 $new_w = $target_w;
                 $new_h = $target_w / $image_ratio;
             } else {
                 $new_h = $target_h;
                 $new_w = $target_h * $image_ratio;
             }
         } else {
             if ($image_w > $image_h) {
                 $new_w = $target_w;
                 $new_h = $target_w / $image_ratio;
             }
             if ($image_h > $image_w) {
                 $new_h = $target_h;
                 $new_w = $target_h * $image_ratio;
             }
         }
     }
     // Default
     if (!isset($new_w)) {
         $new_w = $image_w;
         $new_h = $image_h;
     }
     // Prepare returned array
     $out = array();
     $out['w'] = (int) $new_w;
     $out['h'] = (int) $new_h;
     $out['file_path'] = $save_as;
     $parts = explode(DIRECTORY_SEPARATOR, $save_as);
     $out['file_name'] = array_pop($parts);
     $out['web_path'] = str_replace(PERCH_RESFILEPATH . DIRECTORY_SEPARATOR, PERCH_RESPATH . '/', $save_as);
     $out['density'] = $this->density;
     // If SVG, we can return at this point.
     if ($svg) {
         $out['mime'] = $svg;
         return $out;
     }
     if ($crop) {
         if ($crop_w) {
             $out['w'] = (int) $crop_w;
         }
         if ($crop_h) {
             $out['h'] = (int) $crop_h;
         }
     }
     // Check we're not upsizing
     if ($crop) {
         if ($crop_w > $image_w || $crop_h > $image_h) {
             $bail = true;
         }
     } else {
         if ($new_w > $image_w || $new_h > $image_h) {
             $bail = true;
         }
     }
     // Check we're not resizing to the same exact size, as this just kills quality
     if ($crop) {
         if ($crop_w == $image_w && $crop_h == $image_h) {
             $bail = true;
         }
     } else {
         if ($new_w == $image_w && $new_h == $image_h) {
             $bail = true;
         }
     }
     // Bail?
     if ($bail) {
         copy($image_path, $save_as);
         PerchUtil::set_file_permissions($save_as);
         // reset sizes
         $out['w'] = (int) $image_w;
         $out['h'] = (int) $image_h;
         $Perch->event('assets.create_image', new PerchAssetFile($out));
         return $out;
     }
     // Density
     $new_w = floor($new_w * $this->density);
     $new_h = floor($new_h * $this->density);
     $crop_w = floor($crop_w * $this->density);
     $crop_h = floor($crop_h * $this->density);
     $crop_x = floor($crop_x * $this->density);
     $crop_y = floor($crop_y * $this->density);
     //PerchUtil::debug('Density: '.$this->density);
     $r = false;
     if ($this->mode == 'gd') {
         $r = $this->resize_with_gd($image_path, $save_as, $new_w, $new_h, $crop_w, $crop_h, $crop_x, $crop_y);
     }
     if ($this->mode == 'imagick') {
         $r = $this->resize_with_imagick($image_path, $save_as, $new_w, $new_h, $crop_w, $crop_h, $crop_x, $crop_y);
     }
     if ($r) {
         $out['mime'] = $r;
     }
     PerchUtil::set_file_permissions($save_as);
     $Perch->event('assets.create_image', new PerchAssetFile($out));
     if ($r) {
         return $out;
     }
     return false;
 }
 public function get_filtered_listing_from_index($opts, $where_callback, $pre_template_callback = null)
 {
     $Perch = Perch::fetch();
     $index_table = PERCH_DB_PREFIX . $this->index_table;
     $where = array();
     $filter_mode = false;
     $single_mode = false;
     $content = array();
     // find specific _id
     if (isset($opts['_id'])) {
         $item_id = (int) $opts['_id'];
         $Paging = false;
         $sql = 'SELECT main.* FROM ' . $this->table . ' main WHERE main.' . $this->pk . '=' . $this->db->pdb($item_id) . ' LIMIT 1 ';
         $rows = $this->db->get_rows($sql);
         $single_mode = true;
     } else {
         $sortval = ' idx2.indexValue as sortval ';
         if (isset($opts['paginate']) && $opts['paginate']) {
             if (isset($opts['pagination-var'])) {
                 $Paging = new PerchPaging($opts['pagination-var']);
             } else {
                 $Paging = new PerchPaging();
             }
             $sql = $Paging->select_sql();
         } else {
             $sql = 'SELECT';
         }
         $sql .= ' tbl.* FROM ( SELECT  idx.itemID, main.*, ' . $sortval . ' FROM ' . $index_table . ' idx
                         JOIN ' . $this->table . ' main ON idx.itemID=main.' . $this->pk . ' AND idx.itemKey=' . $this->db->pdb($this->pk) . '
                         JOIN ' . $index_table . ' idx2 ON idx.itemID=idx2.itemID AND idx.itemKey=' . $this->db->pdb($this->pk) . ' ';
         if (isset($opts['sort'])) {
             $sql .= ' AND idx2.indexKey=' . $this->db->pdb($opts['sort']) . ' ';
         } else {
             $sql .= ' AND idx2.indexKey=' . $this->db->pdb('_id') . ' ';
         }
         $where_clause = ' idx.itemKey=' . $this->db->pdb($this->pk) . ' ';
         // Categories
         if (isset($opts['category']) && !$this->bypass_categories) {
             $cats = $opts['category'];
             if (!is_array($cats)) {
                 $cats = array($cats);
             }
             $match = 'any';
             if (isset($opts['category-match'])) {
                 $match = strtolower($opts['category-match']) == 'any' ? 'any' : 'all';
             }
             $pos = array();
             $neg = array();
             if (count($cats)) {
                 foreach ($cats as $cat) {
                     if (substr($cat, 0, 1) == '!') {
                         $neg[] = substr($cat, 1);
                     } else {
                         $pos[] = $cat;
                     }
                 }
                 $sql .= $this->_get_filter_sub_sql('_category', $pos, false, $match, true, $where_clause);
                 $sql .= $this->_get_filter_sub_sql('_category', $neg, true, $match, true, $where_clause);
             }
         }
         // Tags
         if (isset($opts['tag']) && !$this->bypass_tags) {
             $cats = $opts['tag'];
             if (!is_array($cats)) {
                 $cats = array($cats);
             }
             $match = 'any';
             if (isset($opts['tag-match'])) {
                 $match = strtolower($opts['tag-match']) == 'any' ? 'any' : 'all';
             }
             $pos = array();
             $neg = array();
             if (count($cats)) {
                 foreach ($cats as $cat) {
                     if (substr($cat, 0, 1) == '!') {
                         $neg[] = substr($cat, 1);
                     } else {
                         $pos[] = $cat;
                     }
                 }
                 $sql .= $this->_get_filter_sub_sql('_tag', $pos, false, $match, false, $where_clause);
                 $sql .= $this->_get_filter_sub_sql('_tag', $neg, true, $match, false, $where_clause);
             }
         }
         // Runtime restrictons
         if (!$Perch->admin && count($this->runtime_restrictons)) {
             foreach ($this->runtime_restrictons as $res) {
                 $sql .= $this->_get_filter_sub_sql($res['field'], $res['values'], $res['negative_match'], $res['match'], $res['fuzzy'], $where_clause);
             }
         }
         // if not picking an _id, check for a filter
         if (isset($opts['filter']) && (isset($opts['value']) || is_array($opts['filter']))) {
             // if it's not a multi-filter, make it look like one to unify what we're working with
             if (!is_array($opts['filter']) && isset($opts['value'])) {
                 $filters = array(array('filter' => $opts['filter'], 'value' => $opts['value'], 'match' => isset($opts['match']) ? $opts['match'] : 'eq', 'match-type' => isset($opts['match-type']) ? $opts['match-type'] : 'alpha'));
                 $filter_mode = 'AND';
             } else {
                 $filters = $opts['filter'];
                 $filter_mode = 'AND';
                 if (isset($opts['match']) && strtolower($opts['match']) == 'or') {
                     $filter_mode = 'OR';
                 }
             }
             $where = array();
             foreach ($filters as $filter) {
                 $key = $filter['filter'];
                 $val = $filter['value'];
                 $match = isset($filter['match']) ? $filter['match'] : 'eq';
                 if (is_numeric($val)) {
                     $val = (double) $val;
                 }
                 switch ($match) {
                     case 'eq':
                     case 'is':
                     case 'exact':
                         $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue=' . $this->db->pdb($val) . ')';
                         break;
                     case 'neq':
                     case 'ne':
                     case 'not':
                     case '!eq':
                         $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue != ' . $this->db->pdb($val) . ')';
                         break;
                     case 'gt':
                         $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue > ' . $this->db->pdb($val) . ')';
                         break;
                     case '!gt':
                         $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue !> ' . $this->db->pdb($val) . ')';
                         break;
                     case 'gte':
                         $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue >= ' . $this->db->pdb($val) . ')';
                         break;
                     case '!gte':
                         $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue !>= ' . $this->db->pdb($val) . ')';
                         break;
                     case 'lt':
                         $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue < ' . $this->db->pdb($val) . ')';
                         break;
                     case '!lt':
                         $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue !< ' . $this->db->pdb($val) . ')';
                         break;
                     case 'lte':
                         $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue <= ' . $this->db->pdb($val) . ')';
                         break;
                     case '!lte':
                         $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue !<= ' . $this->db->pdb($val) . ')';
                         break;
                     case 'contains':
                         $v = str_replace('/', '\\/', $val);
                         $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue REGEXP ' . $this->db->pdb('[[:<:]]' . $v . '[[:>:]]') . ')';
                         break;
                     case 'notcontains':
                     case '!contains':
                         $v = str_replace('/', '\\/', $val);
                         $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue NOT REGEXP ' . $this->db->pdb('[[:<:]]' . $v . '[[:>:]]') . ')';
                         break;
                     case 'regex':
                     case 'regexp':
                         $v = str_replace('/', '\\/', $val);
                         $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue REGEXP ' . $this->db->pdb($v) . ')';
                         break;
                     case 'between':
                     case 'betwixt':
                         $vals = explode(',', $val);
                         if (PerchUtil::count($vals) == 2) {
                             $vals[0] = trim($vals[0]);
                             $vals[1] = trim($vals[1]);
                             if (is_numeric($vals[0]) && is_numeric($vals[1])) {
                                 $vals[0] = (double) $vals[0];
                                 $vals[1] = (double) $vals[1];
                             }
                             $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND (idx.indexValue > ' . $this->db->pdb($vals[0]) . ' AND idx.indexValue < ' . $this->db->pdb($vals[1]) . '))';
                         }
                         break;
                     case '!between':
                     case '!betwixt':
                         $vals = explode(',', $val);
                         if (PerchUtil::count($vals) == 2) {
                             $vals[0] = trim($vals[0]);
                             $vals[1] = trim($vals[1]);
                             if (is_numeric($vals[0]) && is_numeric($vals[1])) {
                                 $vals[0] = (double) $vals[0];
                                 $vals[1] = (double) $vals[1];
                             }
                             $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND (idx.indexValue !> ' . $this->db->pdb($vals[0]) . ' AND idx.indexValue !< ' . $this->db->pdb($vals[1]) . '))';
                         }
                         break;
                     case 'eqbetween':
                     case 'eqbetwixt':
                         $vals = explode(',', $val);
                         if (PerchUtil::count($vals) == 2) {
                             $vals[0] = trim($vals[0]);
                             $vals[1] = trim($vals[1]);
                             if (is_numeric($vals[0]) && is_numeric($vals[1])) {
                                 $vals[0] = (double) $vals[0];
                                 $vals[1] = (double) $vals[1];
                             }
                             $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND (idx.indexValue >= ' . $this->db->pdb($vals[0]) . ' AND idx.indexValue <= ' . $this->db->pdb($vals[1]) . '))';
                         }
                         break;
                     case '!eqbetween':
                     case '!eqbetwixt':
                         $vals = explode(',', $val);
                         if (PerchUtil::count($vals) == 2) {
                             $vals[0] = trim($vals[0]);
                             $vals[1] = trim($vals[1]);
                             if (is_numeric($vals[0]) && is_numeric($vals[1])) {
                                 $vals[0] = (double) $vals[0];
                                 $vals[1] = (double) $vals[1];
                             }
                             $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND (idx.indexValue !>= ' . $this->db->pdb($vals[0]) . ' AND idx.indexValue !<= ' . $this->db->pdb($vals[1]) . '))';
                         }
                         break;
                     case 'in':
                     case 'within':
                         $vals = explode(',', $val);
                         if (PerchUtil::count($vals)) {
                             $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue IN (' . $this->db->implode_for_sql_in($vals) . '))';
                         }
                         break;
                     case '!in':
                     case '!within':
                         $vals = explode(',', $val);
                         if (PerchUtil::count($vals)) {
                             $where[] = '(idx.indexKey=' . $this->db->pdb($key) . ' AND idx.indexValue NOT IN (' . $this->db->implode_for_sql_in($vals) . '))';
                         }
                         break;
                 }
             }
         }
         $sql .= ' WHERE 1=1 ';
         if (PerchUtil::count($where)) {
             $sql .= ' AND (' . implode($where, ' OR ') . ') ';
         }
         $sql .= ' AND idx.itemID=idx2.itemID AND idx.itemKey=idx2.itemKey
                     GROUP BY idx.itemID
                 ) as tbl ';
         $where = array();
         if (is_callable($where_callback)) {
             // load up Query object
             $Query = new PerchQuery();
             $Query->select = $sql;
             $Query->where = $where;
             // do callback
             $Query = $where_callback($Query);
             // retrieve
             $sql = $Query->select;
             $where = $Query->where;
         }
         if (PerchUtil::count($where)) {
             $sql .= ' WHERE (' . implode($where, ' AND ') . ') ';
         }
         $sql .= 'GROUP BY itemID ';
         if ($filter_mode == 'AND' && PerchUtil::count($filters) > 1) {
             $sql .= ' HAVING count(*)=' . PerchUtil::count($filters) . ' ';
         }
         // sort
         if (isset($opts['sort'])) {
             $direction = 'ASC';
             if (isset($opts['sort-order'])) {
                 switch ($opts['sort-order']) {
                     case 'DESC':
                     case 'desc':
                         $direction = 'DESC';
                         break;
                     case 'RAND':
                     case 'rand':
                         $direction = 'RAND';
                         break;
                     default:
                         $direction = 'ASC';
                         break;
                 }
             }
             if ($direction == 'RAND') {
                 $sql .= ' ORDER BY RAND()';
             } else {
                 if (isset($opts['sort-type']) && $opts['sort-type'] == 'numeric') {
                     $sql .= ' ORDER BY sortval * 1 ' . $direction . ' ';
                 } else {
                     $sql .= ' ORDER BY sortval ' . $direction . ' ';
                 }
             }
         } else {
             if (isset($opts['sort-type']) && $opts['sort-type'] == 'numeric') {
                 $sql .= ' ORDER BY sortval * 1 ASC ';
             } else {
                 $sql .= ' ORDER BY sortval ASC ';
             }
         }
         // Pagination
         if (isset($opts['paginate']) && $opts['paginate']) {
             if (is_object($opts['paginate'])) {
                 $Paging = $opts['paginate'];
             } else {
                 if (isset($opts['pagination-var'])) {
                     $Paging = new PerchPaging($opts['pagination-var']);
                 } else {
                     $Paging = new PerchPaging();
                 }
                 $Paging->set_per_page(isset($opts['count']) ? (int) $opts['count'] : 10);
             }
             $opts['count'] = $Paging->per_page();
             $opts['start'] = $Paging->lower_bound() + 1;
         } else {
             $Paging = false;
         }
         // limit
         if (isset($opts['count']) || isset($opts['start'])) {
             // count
             if (isset($opts['count'])) {
                 $count = (int) $opts['count'];
             } else {
                 $count = false;
             }
             // start
             if (isset($opts['start'])) {
                 $start = (int) $opts['start'] - 1;
             } else {
                 $start = 0;
             }
             if (is_object($Paging)) {
                 $sql .= $Paging->limit_sql();
             } else {
                 $sql .= ' LIMIT ' . $start;
                 if ($count) {
                     $sql .= ', ' . $count;
                 }
             }
         }
         $rows = $this->db->get_rows($sql);
         if (is_object($Paging)) {
             $total_count = $this->db->get_value($Paging->total_count_sql());
             $Paging->set_total($total_count);
         }
         // pre-template callback
         if (PerchUtil::count($rows) && $pre_template_callback && is_callable($pre_template_callback)) {
             $rows = $pre_template_callback($rows);
         }
         // each
         if (PerchUtil::count($rows) && isset($opts['each']) && is_callable($opts['each'])) {
             $content = array();
             foreach ($rows as $item) {
                 $tmp = $opts['each']($item);
                 $content[] = $tmp;
             }
             $rows = $content;
         }
         $items = $this->return_instances($rows);
     }
     if (isset($opts['return-objects']) && $opts['return-objects']) {
         return $items;
     }
     $render_html = true;
     if (isset($opts['skip-template']) && $opts['skip-template'] == true) {
         $render_html = false;
         if (isset($opts['return-html']) && $opts['return-html'] == true) {
             $render_html = true;
         }
     }
     // template
     if (is_callable($opts['template'])) {
         $callback = $opts['template'];
         $template = $callback($items);
     } else {
         $template = $opts['template'];
     }
     if (is_object($this->api)) {
         $Template = $this->api->get('Template');
         $Template->set($template, $this->namespace);
     } else {
         $Template = new PerchTemplate($template, $this->namespace);
     }
     if ($render_html) {
         if (isset($Paging) && is_object($Paging) && $Paging->enabled()) {
             $paging_array = $Paging->to_array($opts);
             // merge in paging vars
             if (PerchUtil::count($items)) {
                 foreach ($items as &$Item) {
                     foreach ($paging_array as $key => $val) {
                         $Item->squirrel($key, $val);
                     }
                 }
             }
         }
         if (PerchUtil::count($items)) {
             if (isset($opts['split-items']) && $opts['split-items']) {
                 $html = $Template->render_group($items, false);
             } else {
                 $html = $Template->render_group($items, true);
             }
         } else {
             $Template->use_noresults();
             $html = $Template->render(array());
         }
     }
     if (isset($opts['skip-template']) && $opts['skip-template'] == true) {
         if ($single_mode) {
             return $Item->to_array();
         }
         $processed_vars = array();
         if (PerchUtil::count($items)) {
             foreach ($items as $Item) {
                 $processed_vars[] = $Item->to_array();
             }
         }
         if (PerchUtil::count($processed_vars)) {
             $category_field_ids = $Template->find_all_tag_ids('categories');
             //PerchUtil::debug($category_field_ids, 'notice');
             foreach ($processed_vars as &$item) {
                 if (PerchUtil::count($item)) {
                     foreach ($item as $key => &$field) {
                         if (in_array($key, $category_field_ids)) {
                             $field = $this->_process_category_field($field);
                         }
                         if (is_array($field) && isset($field['processed'])) {
                             $field = $field['processed'];
                         }
                         if (is_array($field) && isset($field['_default'])) {
                             $field = $field['_default'];
                         }
                     }
                 }
             }
         }
         if (isset($opts['return-html']) && $opts['return-html'] == true) {
             $processed_vars['html'] = $html;
         }
         return $processed_vars;
     }
     if (is_array($html)) {
         // split-items
         if (PerchUtil::count($html)) {
             $Template = new PerchTemplate();
             foreach ($html as &$html_item) {
                 if (strpos($html_item, '<perch:') !== false) {
                     $html_item = $Template->apply_runtime_post_processing($html_item);
                 }
             }
         }
     } else {
         if (strpos($html, '<perch:') !== false) {
             $Template = new PerchTemplate();
             $html = $Template->apply_runtime_post_processing($html);
         }
     }
     return $html;
 }
Example #26
0
 public function send()
 {
     $LogMessage = new PerchSystemEventSubject();
     $LogMessage->recipients = array();
     $LogMessage->attachments = array();
     $body = $this->build_message();
     $LogMessage->body = $body;
     $debug_recipients = array();
     $mail = new PHPMailer(true);
     $mail->CharSet = 'UTF-8';
     $LogMessage->charset = 'utf-8';
     if ($this->html) {
         $mail->IsHTML();
         $mail->AltBody = $this->plain_textify($body);
         $LogMessage->is_html = true;
         $LogMessage->altbody = $mail->AltBody;
     } else {
         $LogMessage->is_html = false;
     }
     try {
         if ($this->replyToEmail()) {
             $mail->AddReplyTo($this->replyToEmail(), $this->replyToName());
             $LogMessage->reply_to = array('email' => $this->replyToEmail(), 'name' => $this->replyToName());
         }
         if (PerchUtil::count($this->bcc_list)) {
             foreach ($this->bcc_list as $bcc) {
                 $mail->addBCC($bcc);
             }
             $LogMessage->bcc = $this->bcc_list;
         }
         $mail->SetFrom($this->senderEmail(), $this->senderName());
         $LogMessage->from = array('email' => $this->senderEmail(), 'name' => $this->senderName());
         if (is_array($this->recipientEmail)) {
             foreach ($this->recipientEmail as $recipient) {
                 $mail->AddAddress($recipient);
                 $debug_recipients[] = $recipient;
                 $LogMessage->recipients[] = $recipient;
             }
         } else {
             $mail->AddAddress($this->recipientEmail(), $this->recipientName());
             $debug_recipients[] = $this->recipientEmail();
             $LogMessage->recipients[] = $this->recipientEmail();
         }
         $mail->Subject = $this->subject();
         $LogMessage->subject = $this->subject();
         $mail->Body = $body;
         if (PerchUtil::count($this->files)) {
             foreach ($this->files as $file) {
                 $mail->AddAttachment($file['path'], $file['name']);
                 // attachment
                 $LogMessage->attachments[] = $file;
             }
         }
         switch (strtolower(PERCH_EMAIL_METHOD)) {
             case 'sendmail':
                 $mail->IsSendmail();
                 $LogMessage->sent_by = 'sendmail';
                 break;
             case 'smtp':
                 $mail->IsSMTP();
                 $mail->Host = PERCH_EMAIL_HOST;
                 $mail->SMTPAuth = PERCH_EMAIL_AUTH;
                 $mail->Port = PERCH_EMAIL_PORT;
                 $mail->Username = PERCH_EMAIL_USERNAME;
                 $mail->Password = PERCH_EMAIL_PASSWORD;
                 $mail->SMTPSecure = PERCH_EMAIL_SECURE;
                 $LogMessage->sent_by = 'smtp';
                 $LogMessage->smtp_host = PERCH_EMAIL_HOST;
                 $LogMessage->smtp_auth = PERCH_EMAIL_AUTH;
                 $LogMessage->smtp_port = PERCH_EMAIL_PORT;
                 $LogMessage->smtp_username = PERCH_EMAIL_USERNAME;
                 $LogMessage->smtp_password = PERCH_EMAIL_PASSWORD;
                 $LogMessage->smtp_secure = PERCH_EMAIL_SECURE;
                 break;
         }
         if (!$mail->Send()) {
             PerchUtil::debug($mail->ErrorInfo, 'error');
             return false;
         } else {
             PerchUtil::debug('Sent email: "' . $this->subject() . '" to ' . implode(', ', $debug_recipients), 'success');
             $Perch = Perch::fetch();
             $Perch->event('email.send', $LogMessage);
             return true;
         }
     } catch (phpmailerException $e) {
         $this->errors .= $e->errorMessage();
     } catch (Exception $e) {
         $this->errors .= $e->getMessage();
     }
     PerchUtil::debug($this->errors, 'error');
     return false;
 }
 /**
  * Reorder keys into source order
  *
  * @return void
  * @author Drew McLellan
  */
 private function _reorder_keys()
 {
     if (PerchUtil::count($this->key_requests)) {
         $Perch = Perch::fetch();
         $page = $Perch->get_page();
         $db = PerchDB::fetch();
         $i = 0;
         foreach ($this->key_requests as $key) {
             if (!in_array($key, $this->keys_reordered)) {
                 $sql = 'UPDATE ' . $this->table . ' SET regionOrder=' . $i . ' WHERE regionPage=' . $db->pdb($page) . ' AND regionKey=' . $db->pdb($key) . ' LIMIT 1';
                 $db->execute($sql);
                 $this->keys_reordered[] = $key;
             }
             $i++;
         }
     }
 }
 /**
  * Take the original uploaded file and make all the different versions, based on the given template.
  *
  * @param string $filename 
  * @param string $Template 
  * @return void
  * @author Drew McLellan
  */
 public function process_versions($filename, $Template, $bucket)
 {
     $this->delete_versions();
     $result = false;
     $image_file = PerchUtil::file_path($bucket['file_path'] . '/' . $filename);
     PerchUtil::debug('123: ' . $image_file);
     if (!file_exists($image_file)) {
         return false;
     }
     $API = new PerchAPI(1.0, 'perch_gallery');
     $Image = $API->get('Image');
     $Versions = new PerchGallery_ImageVersions();
     $tags = $Template->find_all_tags();
     $Perch = Perch::fetch();
     if (!is_array($tags)) {
         $tags = array();
     }
     // add defaults we need for admin
     $tags[] = new PerchXMLTag('<perch:gallery id="image" type="image" />');
     // default full size
     $tags[] = new PerchXMLTag('<perch:gallery id="image" type="image" width="80" height="80" crop="true" key="admin_thumb" />');
     // admin thumb
     $tags[] = new PerchXMLTag('<perch:gallery id="image" type="image" width="180" key="admin_preview" />');
     // admin preview
     if (PerchUtil::count($tags)) {
         foreach ($tags as $Tag) {
             if ($Tag->id() == 'image' && $Tag->type() == 'image') {
                 //$bucket = $Perch->get_resource_bucket($Tag->bucket());
                 $Image->reset_defaults();
                 if ($Tag->quality()) {
                     $Image->set_quality($Tag->quality());
                 }
                 if ($Tag->sharpen()) {
                     $Image->set_sharpening($Tag->sharpen());
                 }
                 if ($Tag->density()) {
                     $Image->set_density($Tag->density());
                 }
                 if ($Tag->width() || $Tag->height()) {
                     $details = $Image->resize_image($image_file, $Tag->width(), $Tag->height(), $Tag->crop());
                 } else {
                     $details = array();
                     $details['file_name'] = $filename;
                     PerchUtil::debug('152: ' . $filename);
                     $info = getimagesize($image_file);
                     if (is_array($info)) {
                         $details['w'] = $info[0];
                         $details['h'] = $info[1];
                     }
                 }
                 if ($details) {
                     $data = array();
                     $data['imageID'] = $this->id();
                     if (strpos($details['file_name'], DIRECTORY_SEPARATOR) !== false) {
                         $parts = explode(DIRECTORY_SEPARATOR, $details['file_name']);
                         $details['file_name'] = array_pop($parts);
                     }
                     $data['versionPath'] = $details['file_name'];
                     //PerchUtil::debug('167: '. $details['file_name']);
                     if ($Tag->key()) {
                         $data['versionKey'] = $Tag->key();
                     } else {
                         $data['versionKey'] = $this->_generate_version_key($Tag->width(), $Tag->height());
                     }
                     if ($Tag->crop()) {
                         $data['versionWidth'] = $Tag->width();
                         $data['versionHeight'] = $Tag->height();
                     } else {
                         $data['versionWidth'] = $details['w'];
                         $data['versionHeight'] = $details['h'];
                     }
                     $Version = $Versions->create($data);
                     if (is_object($Version)) {
                         $result = true;
                     }
                 }
             }
         }
     }
     return $result;
 }
 public function authenticate($username, $password)
 {
     // Passwords should never be longer than 72 characters
     if (strlen($password) > 72) {
         return false;
     }
     $username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
     if ($this->activate()) {
         if (PERCH_PARANOID) {
             // reset any expired lockouts for this user
             $sql = 'UPDATE ' . $this->table . ' SET userLastFailedLogin=NULL, userFailedLoginAttempts=0
                     WHERE BINARY userUsername='******' 
                         AND userLastFailedLogin<' . $this->db->pdb(date('Y-m-d H:i:s', strtotime('-' . PERCH_AUTH_LOCKOUT_DURATION)));
             $this->db->execute($sql);
         }
         $sql = 'SELECT u.*, r.* FROM ' . $this->table . ' u, ' . PERCH_DB_PREFIX . 'user_roles r
                     WHERE u.roleID=r.roleID AND u.userEnabled=1 AND ';
         if (PERCH_PARANOID) {
             $sql .= 'BINARY userUsername='******' AND userFailedLoginAttempts<' . (int) PERCH_MAX_FAILED_LOGINS;
         } else {
             $sql .= 'userUsername='******' LIMIT 1';
         $result = $this->db->get_row($sql);
         if (is_array($result)) {
             PerchUtil::debug('User exists, checking password.');
             // presume password fail.
             $password_match = false;
             $stored_password = $result['userPassword'];
             $Hasher = PerchUtil::get_password_hasher();
             // data array for user details - gets committed if passwords check out.
             $data = array();
             // check password type
             if (substr($stored_password, 0, 3) == '$P$') {
                 PerchUtil::debug('Stronger password hash.');
                 // stronger hash, check password
                 if ($Hasher->CheckPassword($password, $stored_password)) {
                     $password_match = true;
                     PerchUtil::debug('Password is ok.');
                 } else {
                     PerchUtil::debug('Password failed to match.');
                 }
             } else {
                 // old MD5 password
                 PerchUtil::debug('Old MD5 password.');
                 if ($stored_password == md5($password)) {
                     $password_match = true;
                     PerchUtil::debug('Password is ok. Upgrading.');
                     //upgrade!
                     $hashed_password = $Hasher->HashPassword($password);
                     $data['userPassword'] = $hashed_password;
                 } else {
                     PerchUtil::debug('MD5 password failed to match.');
                 }
             }
             if ($password_match) {
                 $this->set_details($result);
                 $data['userHash'] = md5(uniqid());
                 $data['userLastLogin'] = date('Y-m-d H:i:s');
                 $data['userFailedLoginAttempts'] = 0;
                 $data['userLastFailedLogin'] = null;
                 $this->update($data);
                 $this->result['userHash'] = $data['userHash'];
                 $this->set_details($result);
                 PerchSession::regenerate();
                 PerchSession::set('userID', $result['userID']);
                 PerchSession::set('userHash', $data['userHash']);
                 $this->logged_in = true;
                 $this->_load_privileges();
                 if (!$this->has_priv('perch.login')) {
                     PerchUtil::debug('User role does not have login privs');
                     $this->logout();
                     return false;
                 }
                 // Set cookie for front-end might-be-authed check
                 PerchUtil::setcookie('cmsa', 1, strtotime('+30 days'), '/');
                 $Perch = Perch::fetch();
                 $Perch->event('user.login', $this);
                 return true;
             }
             // Username checks out, but wrong password.
             $data['userFailedLoginAttempts'] = (int) $result['userFailedLoginAttempts'] + 1;
             $data['userLastFailedLogin'] = date('Y-m-d H:i:s');
             $this->set_details($result);
             $this->update($data);
             if (PERCH_PARANOID && $data['userFailedLoginAttempts'] == PERCH_MAX_FAILED_LOGINS) {
                 $this->send_lockout_email($result['userID']);
             }
         }
     }
     PerchUtil::debug('Writing auth fail to log.');
     $username = escapeshellcmd(stripslashes($username));
     @syslog(LOG_INFO, 'Authentication failure for ' . $username . ' from ' . PerchUtil::get_client_ip());
     return false;
 }
 private static function make_request($type, $data)
 {
     $Perch = Perch::fetch();
     $request = http_build_query($data);
     $host = self::$apiKey . '.' . self::$host;
     $path = '/1.1/' . $type;
     $port = 80;
     $akismet_ua = "Perch/" . $Perch->version . " | perch_comments";
     $content_length = strlen($request);
     $http_request = "POST {$path} HTTP/1.0\r\n";
     $http_request .= "Host: {$host}\r\n";
     $http_request .= "Content-Type: application/x-www-form-urlencoded\r\n";
     $http_request .= "Content-Length: {$content_length}\r\n";
     $http_request .= "User-Agent: {$akismet_ua}\r\n";
     $http_request .= "\r\n";
     $http_request .= $request;
     $response = '';
     if (false != ($fs = @fsockopen($host, $port, $errno, $errstr, 10))) {
         fwrite($fs, $http_request);
         while (!feof($fs)) {
             $response .= fgets($fs, 1160);
         }
         // One TCP-IP packet
         fclose($fs);
         $response = explode("\r\n\r\n", $response, 2);
     }
     if (isset($response[1])) {
         return $response[1];
     }
     return false;
 }