public function to_array($template_ids = false, $PerchGallery_ImageVersions = false)
 {
     $out = parent::to_array();
     if ($out['imageDynamicFields'] != '') {
         $dynamic_fields = PerchUtil::json_safe_decode($out['imageDynamicFields'], true);
         if (PerchUtil::count($dynamic_fields)) {
             foreach ($dynamic_fields as $key => $value) {
                 $out['perch_' . $key] = $value;
             }
         }
         $out = array_merge($dynamic_fields, $out);
     }
     $versions = $this->get_versions_for_image($PerchGallery_ImageVersions);
     if (PerchUtil::count($versions)) {
         $bucket_name = $this->details['imageBucket'];
         $Perch = Perch::fetch();
         $bucket = $Perch->get_resource_bucket($bucket_name);
         foreach ($versions as $Version) {
             $out[$Version->versionKey()] = $Version->path($bucket);
             $out[$Version->versionKey() . '-w'] = $Version->versionWidth();
             $out[$Version->versionKey() . '-h'] = $Version->versionHeight();
             $out[$Version->versionKey() . '-id'] = $Version->versionID();
             $out[$Version->versionKey() . '-key'] = $Version->versionKey();
         }
     }
     $out['_id'] = $this->id();
     return $out;
 }
 /**
  * Create a new session, add it to the session store, set the cookie, expire any old sessions
  * @param  integer $memberID [description]
  * @return [type]            [description]
  */
 protected function _generate_session($user_row = false)
 {
     $session_id = sha1(uniqid(mt_rand(), true));
     $http_footprint = $this->_get_http_footprint();
     if (PerchUtil::count($user_row)) {
         $memberID = $user_row['memberID'];
         if (isset($user_row['memberProperties']) && $user_row['memberProperties'] != '') {
             $properties = PerchUtil::json_safe_decode($user_row['memberProperties'], true);
             $user_row = array_merge($properties, $user_row);
             unset($user_row['memberProperties']);
         }
         $session_data = $user_row;
         $session_data['tags'] = $this->_load_tags($memberID);
         $session_data['token'] = $this->_generate_csrf_token($session_id);
     } else {
         $memberID = 0;
         $session_data = array();
     }
     $data = array('sessionID' => $session_id, 'sessionExpires' => date('Y-m-d H:i:s', strtotime(' + ' . PERCH_MEMBERS_SESSION_TIME)), 'sessionHttpFootprint' => $http_footprint, 'memberID' => $memberID, 'sessionData' => serialize($session_data));
     if ($this->db->insert(PERCH_DB_PREFIX . 'members_sessions', $data)) {
         PerchUtil::setcookie(PERCH_MEMBERS_COOKIE, $session_id, '', '/', '', '', true);
         $_COOKIE[PERCH_MEMBERS_COOKIE] = $session_id;
         $this->_expire_old_sessions();
     }
 }
 public function to_array($template_ids = false, $PerchGallery_ImageVersions = false)
 {
     $out = parent::to_array();
     if ($out['imageDynamicFields'] != '') {
         $dynamic_fields = PerchUtil::json_safe_decode($out['imageDynamicFields'], true);
         if (PerchUtil::count($dynamic_fields)) {
             foreach ($dynamic_fields as $key => $value) {
                 $out['perch_' . $key] = $value;
             }
         }
         $out = array_merge($dynamic_fields, $out);
     }
     $versions = $this->get_versions_for_image($PerchGallery_ImageVersions);
     if (PerchUtil::count($versions)) {
         foreach ($versions as $Version) {
             $out[$Version->versionKey()] = PERCH_RESPATH . '/' . $Version->versionPath();
             $out[$Version->versionKey() . '-w'] = $Version->versionWidth();
             $out[$Version->versionKey() . '-h'] = $Version->versionHeight();
             $out[$Version->versionKey() . '-id'] = $Version->versionID();
             $out[$Version->versionKey() . '-key'] = $Version->versionKey();
         }
     }
     $out['_id'] = $this->id();
     return $out;
 }
 /**
  * Return property from the userAccountData json store
  * with an optional default for missing values
  *
  * @param $key
  * @param null $default
  * @return null
  */
 public function userProperty($key, $default = null)
 {
     $accountData = PerchUtil::json_safe_decode($this->userAccountData(), true);
     if (isset($accountData[$key]) && $accountData[$key]) {
         return $accountData[$key];
     }
     return $default;
 }
 /**
  * Fetch the unique stored users from the database and
  * decode the stored user data.
  *
  * @return array
  */
 public function get_stored_users_unique()
 {
     $return = array();
     $sql = "SELECT `userAccountData` FROM " . $this->table . " GROUP BY `userAccountID` ORDER BY `actionDateTime` DESC";
     $results = $this->db->get_rows($sql);
     if (PerchUtil::count($results)) {
         foreach ($results as $row) {
             $return[] = PerchUtil::json_safe_decode($row['userAccountData'], true);
         }
     }
     return $return;
 }
 public function to_array()
 {
     $out = parent::to_array();
     if ($out['categoryDynamicFields'] != '') {
         $dynamic_fields = PerchUtil::json_safe_decode($out['categoryDynamicFields'], true);
         if (PerchUtil::count($dynamic_fields)) {
             foreach ($dynamic_fields as $key => $value) {
                 $out['perch_' . $key] = $value;
             }
         }
         $out = array_merge($dynamic_fields, $out);
     }
     return $out;
 }
 public function to_array()
 {
     $out = $this->details;
     $dynamic_field_col = str_replace('ID', 'DynamicFields', $this->pk);
     if (isset($out[$dynamic_field_col]) && $out[$dynamic_field_col] != '') {
         $dynamic_fields = PerchUtil::json_safe_decode($out[$dynamic_field_col], true);
         if (PerchUtil::count($dynamic_fields)) {
             foreach ($dynamic_fields as $key => $value) {
                 $out['perch_' . $key] = $value;
             }
             $out = array_merge($dynamic_fields, $out);
         }
     }
     return $out;
 }
 public function get_members($status, $Paging = false)
 {
     $out = $this->get_by('memberStatus', $status, $Paging);
     $sql = 'SELECT c.*
             FROM ' . $this->table . ' c';
     if ($status != 'ALL') {
         $sql .= ' WHERE c.memberStatus=' . $this->db->pdb($status);
     }
     $members = $this->db->get_rows($sql);
     foreach ($members as $key => $value) {
         $dynamic_fields = PerchUtil::json_safe_decode($value['memberProperties'], true);
         foreach ($dynamic_fields as $dynamic_fields_key => $dynamic_fields_value) {
             $members[$key][$dynamic_fields_key] = $dynamic_fields_value;
         }
     }
     return $members;
 }
 public function mark_as_spam()
 {
     $data = array();
     $data['responseSpam'] = '1';
     $this->update($data);
     $json = PerchUtil::json_safe_decode($this->responseSpamData(), true);
     if (PerchUtil::count($json)) {
         $API = new PerchAPI(1, 'perch_forms');
         $Forms = new PerchForms_Forms($API);
         $Form = $Forms->find($this->formID());
         if ($Form) {
             $opts = $Form->get_settings();
             if (isset($opts['akismet']) && $opts['akismet']) {
                 if (isset($opts['akismetAPIKey']) && $opts['akismetAPIKey'] != '') {
                     PerchForms_Akismet::submit_spam($opts['akismetAPIKey'], $json['fields'], $json['environment']);
                 }
             }
         }
     }
 }
 private function load_translations()
 {
     $out = false;
     if (file_exists($this->lang_file)) {
         $json = file_get_contents($this->lang_file);
         $out = PerchUtil::json_safe_decode($json, true);
     } else {
         if (is_writable($this->lang_dir)) {
             touch($this->lang_file);
         }
         $out = array();
     }
     if (is_array($out)) {
         $this->translations = $out;
     } else {
         $json = file_get_contents($this->lang_dir . DIRECTORY_SEPARATOR . 'en-gb.txt');
         $this->translations = PerchUtil::json_safe_decode($json, true);
         PerchUtil::debug('Unable to load language file: ' . $this->lang, 'error');
     }
 }
 /**
  * Get a flat array of the items (or single item) in a region, for the edit form
  *
  * @param string $regionID
  * @param string $rev
  * @param string $item_id
  * @return void
  * @author Drew McLellan
  */
 public function get_flat_for_region($regionID, $rev, $item_id = false, $limit = false)
 {
     $sql = 'SELECT * FROM ' . $this->table . '
             WHERE regionID=' . $this->db->pdb((int) $regionID) . ' AND itemRev=' . $this->db->pdb((int) $rev);
     if ($item_id !== false) {
         $sql .= ' AND itemID=' . $this->db->pdb((int) $item_id);
     }
     $sql .= ' ORDER BY itemOrder ASC';
     if ($limit !== false) {
         $sql .= ' LIMIT ' . intval($limit);
     }
     $rows = $this->db->get_rows($sql);
     if (PerchUtil::count($rows)) {
         foreach ($rows as &$row) {
             $fields = PerchUtil::json_safe_decode($row['itemJSON'], true);
             if (is_array($fields)) {
                 $row = array_merge($fields, $row);
             }
         }
     }
     return $rows;
 }
 public function to_array($template_ids = false)
 {
     $out = parent::to_array();
     if (PerchUtil::count($template_ids) && in_array('postURL', $template_ids)) {
         $API = new PerchAPI(1.0, 'perch_blog');
         $Posts = new PerchBlog_Posts($API);
         $Post = $Posts->find($this->postID());
         if (is_object($Post)) {
             $out['postURL'] = $Post->postURL();
         }
     }
     if ($out['commentDynamicFields'] != '') {
         $dynamic_fields = PerchUtil::json_safe_decode($out['commentDynamicFields'], true);
         if (PerchUtil::count($dynamic_fields)) {
             foreach ($dynamic_fields as $key => $value) {
                 $out['perch_' . $key] = $value;
             }
         }
         $out = array_merge($dynamic_fields, $out);
     }
     return $out;
 }
 public function to_array()
 {
     $out = parent::to_array();
     if ($out['listingDynamicFields'] != '') {
         $dynamic_fields = PerchUtil::json_safe_decode($out['listingDynamicFields'], true);
         if (PerchUtil::count($dynamic_fields)) {
             foreach ($dynamic_fields as $key => $value) {
                 $out['perch_' . $key] = $value;
             }
         }
         $out = array_merge($dynamic_fields, $out);
     }
     if (isset($out['memberProperties']) && $out['memberProperties'] != '') {
         $dynamic_fields = PerchUtil::json_safe_decode($out['memberProperties'], true);
         if (PerchUtil::count($dynamic_fields)) {
             foreach ($dynamic_fields as $key => $value) {
                 $out['perch_' . $key] = $value;
             }
         }
         $out = array_merge($dynamic_fields, $out);
     }
     return $out;
 }
 public function to_array($template_ids = false)
 {
     $out = parent::to_array();
     $Categories = new PerchEvents_Categories();
     $cats = $Categories->get_for_event($this->id());
     $out['category_slugs'] = '';
     $out['category_names'] = '';
     if (PerchUtil::count($cats)) {
         $slugs = array();
         $names = array();
         foreach ($cats as $Category) {
             $slugs[] = $Category->categorySlug();
             $names[] = $Category->categoryTitle();
             // for template
             $out[$Category->categorySlug()] = true;
         }
         $out['category_slugs'] = implode(' ', $slugs);
         $out['category_names'] = implode(', ', $names);
     }
     if (PerchUtil::count($template_ids) && in_array('eventURL', $template_ids)) {
         $Settings = PerchSettings::fetch();
         $url_template = $Settings->get('perch_events_detail_url')->val();
         $this->tmp_url_vars = $out;
         $out['eventURL'] = preg_replace_callback('/{([A-Za-z0-9_\\-]+)}/', array($this, "substitute_url_vars"), $url_template);
         $this->tmp_url_vars = false;
     }
     if (isset($out['eventDynamicFields']) && $out['eventDynamicFields'] != '') {
         $dynamic_fields = PerchUtil::json_safe_decode($out['eventDynamicFields'], true);
         if (PerchUtil::count($dynamic_fields)) {
             foreach ($dynamic_fields as $key => $value) {
                 $out['perch_' . $key] = $value;
             }
         }
         $out = array_merge($dynamic_fields, $out);
     }
     return $out;
 }
 private function activate()
 {
     /*
         Any attempt to circumvent activation invalidates your license.
         We're a small company trying to make something useful at a fair price.
         Please don't steal from us.
     */
     $Perch = PerchAdmin::fetch();
     $host = 'activation.grabaperch.com';
     $path = '/activate/';
     $url = 'http://' . $host . $path;
     $data = '';
     $data['key'] = PERCH_LICENSE_KEY;
     $data['host'] = $_SERVER['SERVER_NAME'];
     $data['version'] = $Perch->version;
     $data['php'] = phpversion();
     $content = http_build_query($data);
     $result = false;
     $use_curl = false;
     if (function_exists('curl_init')) {
         $use_curl = true;
     }
     if ($use_curl) {
         PerchUtil::debug('Activating via CURL');
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
         $result = curl_exec($ch);
         PerchUtil::debug($result);
         $http_status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
         if ($http_status != 200) {
             $result = false;
             PerchUtil::debug('Not HTTP 200: ' . $http_status);
         }
         curl_close($ch);
     } else {
         if (function_exists('fsockopen')) {
             PerchUtil::debug('Activating via sockets');
             $fp = fsockopen($host, 80, $errno, $errstr, 10);
             if ($fp) {
                 $out = "POST {$path} HTTP/1.1\r\n";
                 $out .= "Host: {$host}\r\n";
                 $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
                 $out .= "Content-Length: " . strlen($content) . "\r\n";
                 $out .= "Connection: Close\r\n\r\n";
                 $out .= $content . "\r\n";
                 fwrite($fp, $out);
                 stream_set_timeout($fp, 10);
                 while (!feof($fp)) {
                     $result .= fgets($fp, 128);
                 }
                 fclose($fp);
             }
             if ($result != '') {
                 $parts = preg_split('/[\\n\\r]{4}/', $result);
                 if (is_array($parts)) {
                     $result = $parts[1];
                 }
             }
         }
     }
     // Should have a $result now
     if ($result) {
         $json = PerchUtil::json_safe_decode($result);
         if (is_object($json) && $json->result == 'SUCCESS') {
             // update latest version setting
             $Settings = new PerchSettings();
             $Settings->set('latest_version', $json->latest_version);
             $Settings->set('on_sale_version', $json->on_sale_version);
             PerchUtil::debug($json);
             PerchUtil::debug('Activation: success');
             return true;
         } else {
             PerchUtil::debug('Activation: failed');
             $this->activation_failed = true;
             return false;
         }
     }
     // If activation can't complete, assume honesty. That's how I roll.
     return true;
 }
 private function load_translations()
 {
     $out = false;
     if (file_exists($this->lang_file)) {
         $json = file_get_contents($this->lang_file);
         $out = PerchUtil::json_safe_decode($json, true);
     }
     if (is_array($out)) {
         $this->translations = $out;
     } else {
         $json = file_get_contents(PerchUtil::file_path(PERCH_CORE . '/lang/en-gb.txt'));
         $this->translations = PerchUtil::json_safe_decode($json, true);
         PerchUtil::debug('Unable to load language file: ' . $this->lang, 'error');
     }
 }
 public function to_array($template_ids = false)
 {
     $out = parent::to_array();
     if (isset($out['pageAttributes']) && $out['pageAttributes'] != '') {
         $dynamic_fields = PerchUtil::json_safe_decode($out['pageAttributes'], true);
         if (PerchUtil::count($dynamic_fields)) {
             foreach ($dynamic_fields as $key => $value) {
                 $out['perch_' . $key] = $value;
             }
         }
         $out = array_merge($dynamic_fields, $out);
     }
     $out = array_merge($out, PerchSystem::get_attr_vars());
     return $out;
 }
 private function _process_map($id, $tag, $value)
 {
     $out = array();
     if (isset($value['adr'])) {
         $out['adr'] = $value['adr'];
         $out['_title'] = $value['adr'];
         $out['_default'] = $value['adr'];
         if (!isset($value['lat'])) {
             $lat = false;
             $lng = false;
             $path = '/maps/api/geocode/json?address=' . urlencode($value['adr']) . '&sensor=false';
             $result = PerchUtil::http_get_request('http://', 'maps.googleapis.com', $path);
             if ($result) {
                 $result = PerchUtil::json_safe_decode($result, true);
                 //PerchUtil::debug($result);
                 if ($result['status'] == 'OK') {
                     if (isset($result['results'][0]['geometry']['location']['lat'])) {
                         $lat = $result['results'][0]['geometry']['location']['lat'];
                         $lng = $result['results'][0]['geometry']['location']['lng'];
                     }
                 }
             }
         } else {
             $lat = $value['lat'];
             $lng = $value['lng'];
         }
         $out['lat'] = $lat;
         $out['lng'] = $lng;
         if (!isset($value['clat'])) {
             $clat = $lat;
             $clng = $lng;
         } else {
             $clat = $value['clat'];
             $clng = $value['clng'];
         }
         $out['clat'] = $clat;
         $out['clng'] = $clng;
         if (!isset($value['zoom'])) {
             if ($tag->zoom()) {
                 $zoom = $tag->zoom();
             } else {
                 $zoom = 15;
             }
         } else {
             $zoom = $value['zoom'];
         }
         if (!isset($value['type'])) {
             if ($tag->type()) {
                 $type = $tag->type();
             } else {
                 $type = 'roadmap';
             }
         } else {
             $type = $value['type'];
         }
         $adr = $value['adr'];
         if (PERCH_RWD) {
             $width = $tag->width() ? $tag->width() : '';
             $height = $tag->height() ? $tag->height() : '';
         } else {
             $width = $tag->width() ? $tag->width() : '460';
             $height = $tag->height() ? $tag->height() : '320';
         }
         $static_width = $width == '' ? '460' : $width;
         $static_height = $height == '' ? '320' : $height;
         $out['zoom'] = $zoom;
         $out['type'] = $type;
         $r = '<img id="cmsmap' . PerchUtil::html($id) . '" src="//maps.google.com/maps/api/staticmap';
         $r .= '?center=' . $clat . ',' . $clng . '&amp;size=' . $static_width . 'x' . $static_height . '&amp;zoom=' . $zoom . '&amp;maptype=' . $type;
         if ($lat && $lng) {
             $r .= '&amp;markers=color:red|color:red|' . $lat . ',' . $lng;
         }
         $r .= '" ';
         if ($tag->class()) {
             $r .= ' class="' . PerchUtil::html($tag->class()) . '"';
         }
         $r .= ' width="' . $static_width . '" height="' . $static_height . '" alt="' . PerchUtil::html($adr) . '" />';
         $out['admin_html'] = $r;
         $map_js_path = PerchUtil::html(PERCH_LOGINPATH) . '/core/assets/js/public_maps.min.js';
         if (defined('PERCH_MAP_JS') && PERCH_MAP_JS) {
             $map_js_path = PerchUtil::html(PERCH_MAP_JS);
         }
         // JavaScript
         $r .= '<script type="text/javascript">/* <![CDATA[ */ ';
         $r .= "if(typeof CMSMap =='undefined'){var CMSMap={};CMSMap.maps=[];document.write('<scr'+'ipt type=\"text\\/javascript\" src=\"" . $map_js_path . "\"><'+'\\/sc'+'ript>');}";
         $r .= "CMSMap.maps.push({'mapid':'cmsmap" . PerchUtil::html($id) . "','width':'" . $width . "','height':'" . $height . "','type':'" . $type . "','zoom':'" . $zoom . "','adr':'" . addslashes(PerchUtil::html($adr)) . "','lat':'" . $lat . "','lng':'" . $lng . "','clat':'" . $clat . "','clng':'" . $clng . "'});";
         $r .= '/* ]]> */';
         $r .= '</script>';
         if (defined('PERCH_XHTML_MARKUP') && PERCH_XHTML_MARKUP == false) {
             $r = str_replace('/>', '>', $r);
         }
         $out['html'] = $r;
     }
     return $out;
 }
 public function import_legacy_categories()
 {
     $sql = 'SELECT c.categoryCoreID AS newID
             FROM ' . PERCH_DB_PREFIX . 'blog_posts_to_categories p2c, ' . PERCH_DB_PREFIX . 'blog_categories c
             WHERE p2c.categoryID=c.categoryID AND p2c.postID=' . $this->db->pdb((int) $this->id());
     $catIDs = $this->db->get_rows_flat($sql);
     if (PerchUtil::count($catIDs)) {
         $json = PerchUtil::json_safe_decode($this->postDynamicFields(), true);
         if ($json) {
             $json['categories'] = $catIDs;
         } else {
             $json = array('categories' => $catIDs);
         }
         $this->update(array('postDynamicFields' => PerchUtil::json_safe_encode($json)), false, false);
     }
 }
    foreach ($responses as $Response) {
        ?>
            <tr>
                <td class="primary"><a href="<?php 
        echo $API->app_path();
        ?>
/responses/detail/?id=<?php 
        echo $HTML->encode(urlencode($Response->id()));
        ?>
"><?php 
        echo $HTML->encode(strftime('%d %b %Y %H:%M', strtotime($Response->responseCreated())));
        ?>
</a></td>
                <td>
                    <?php 
        $details = PerchUtil::json_safe_decode($Response->responseJSON(), true);
        $out = array();
        if (PerchUtil::count($details)) {
            foreach ($details['fields'] as $item) {
                if (isset($item['attributes']['label'])) {
                    $out[] = '<strong>' . $HTML->encode($item['attributes']['label']) . ':</strong> ' . $HTML->encode(PerchUtil::excerpt($item['value'], 10));
                }
            }
            echo implode('<br />', $out);
        }
        ?>
                </td>
                <td><a href="<?php 
        echo $API->app_path();
        ?>
/responses/delete/?id=<?php 
 /**
  * Add the content of this region into the content index
  * @param  boolean $item_id [description]
  * @param  boolean $rev [description]
  * @return [type]       [description]
  */
 public function index($rev = false)
 {
     if ($rev === false) {
         $rev = $this->regionLatestRev();
     }
     $Items = new PerchContent_Items();
     // clear out old items
     $sql = 'DELETE FROM ' . PERCH_DB_PREFIX . 'content_index 
             WHERE regionID=' . $this->db->pdb((int) $this->id()) . ' AND itemRev<' . $this->db->pdb((int) $Items->get_oldest_rev($this->id()));
     $this->db->execute($sql);
     $items = $Items->get_for_region($this->id(), $rev);
     if (PerchUtil::count($items)) {
         $sql = 'DELETE FROM ' . PERCH_DB_PREFIX . 'content_index 
                 WHERE regionID=' . $this->db->pdb((int) $this->id()) . ' AND itemRev=' . $this->db->pdb((int) $rev);
         $this->db->execute($sql);
         $Template = new PerchTemplate('content/' . $this->regionTemplate(), 'content');
         $tags = $Template->find_all_tags_and_repeaters('content');
         $tag_index = array();
         if (PerchUtil::count($tags)) {
             foreach ($tags as $Tag) {
                 if (!isset($tag_index[$Tag->id()])) {
                     $tag_index[$Tag->id()] = $Tag;
                 }
             }
         }
         foreach ($items as $Item) {
             $fields = PerchUtil::json_safe_decode($Item->itemJSON(), true);
             $sql = 'INSERT INTO ' . PERCH_DB_PREFIX . 'content_index (itemID, regionID, pageID, itemRev, indexKey, indexValue) VALUES ';
             $values = array();
             $id_set = false;
             if (PerchUtil::count($fields)) {
                 foreach ($fields as $key => $value) {
                     if (isset($tag_index[$key])) {
                         $tag = $tag_index[$key];
                         if ($tag->no_index()) {
                             continue;
                         }
                         if ($tag->type() == 'PerchRepeater') {
                             $index_value = $tag->get_index($value);
                         } else {
                             $FieldType = PerchFieldTypes::get($tag->type(), false, $tag);
                             $index_value = $FieldType->get_index($value);
                         }
                         if (is_array($index_value)) {
                             foreach ($index_value as $index_item) {
                                 $data = array();
                                 $data['itemID'] = (int) $Item->itemID();
                                 $data['regionID'] = (int) $this->id();
                                 $data['pageID'] = (int) $Item->pageID();
                                 $data['itemRev'] = (int) $Item->itemRev();
                                 $data['indexKey'] = $this->db->pdb(substr($index_item['key'], 0, 64));
                                 $data['indexValue'] = $this->db->pdb(substr($index_item['value'], 0, 255));
                                 $values[] = '(' . implode(',', $data) . ')';
                                 if ($index_item['key'] == '_id') {
                                     $id_set = true;
                                 }
                             }
                         }
                     }
                 }
             }
             // _id
             if (!$id_set) {
                 $data = array();
                 $data['itemID'] = (int) $Item->itemID();
                 $data['regionID'] = (int) $this->id();
                 $data['pageID'] = (int) $Item->pageID();
                 $data['itemRev'] = (int) $Item->itemRev();
                 $data['indexKey'] = $this->db->pdb('_id');
                 $data['indexValue'] = (int) $Item->itemID();
                 $values[] = '(' . implode(',', $data) . ')';
             }
             // natural order
             $data = array();
             $data['itemID'] = (int) $Item->itemID();
             $data['regionID'] = (int) $this->id();
             $data['pageID'] = (int) $Item->pageID();
             $data['itemRev'] = (int) $Item->itemRev();
             $data['indexKey'] = $this->db->pdb('_order');
             $data['indexValue'] = $this->db->pdb($Item->itemOrder());
             $values[] = '(' . implode(',', $data) . ')';
             $sql .= implode(',', $values);
             $this->db->execute($sql);
         }
     }
     // optimize index
     $sql = 'OPTIMIZE TABLE ' . PERCH_DB_PREFIX . 'content_index';
     $this->db->get_row($sql);
     $Perch = Perch::fetch();
     $Perch->event('region.index', $this);
 }


<?php 
if (PerchUtil::count($members)) {
    echo '<table class="d itemlist">';
    echo '<thead>';
    echo '<tr>';
    echo '<th>' . $Lang->get('Member Name') . '</th>';
    echo '<th class="last">' . $Lang->get('Created') . '</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';
    foreach ($members as $Member) {
        if ($Member->memberStatus() == 'active') {
            $memberProperties = PerchUtil::json_safe_decode($Member->memberProperties(), true);
            echo '<tr>';
            echo '<td class="primary">';
            echo '<a href="' . PerchUtil::html(PERCH_LOGINPATH . '/addons/apps/perch_members/edit/?id=' . $Member->id()) . '">';
            echo $memberProperties['first_name'] . ' ' . $memberProperties['last_name'];
            echo '</a>';
            echo '</td>';
            echo '<td>';
            echo '<span class="note">' . PerchUtil::html(strftime('%d %b %Y', strtotime($Member->memberCreated()))) . '</span>';
            echo '</td>';
            echo '</tr>';
        }
    }
    echo '</tbody>';
    echo '</table>';
    if ($Paging->enabled()) {
if (!$CurrentUser->has_priv('content.pages.attributes')) {
    PerchUtil::redirect(PERCH_LOGINPATH . '/core/apps/content/');
}
// Page attributes
$API = new PerchAPI(1.0, 'perch_pages');
$Page->api($API);
$Template = $API->get('Template');
$status = $Template->set('pages/attributes/' . $Page->pageAttributeTemplate(), 'pages');
if ($status == 404) {
    $Alert->set('notice', PerchLang::get('The page attribute template (%s) could not be found.', '<code>templates/pages/attributes/' . $Page->pageAttributeTemplate() . '</code>'));
}
$details = $Page->to_array();
$Form = $API->get('Form');
$Form->handle_empty_block_generation($Template);
$req = array();
$req['pageTitle'] = "Required";
$req['pageNavText'] = "Required";
$Form->set_required($req);
$Form->set_required_fields_from_template($Template, $details, array('pageTitle', 'pageNavText'));
if ($Form->posted() && $Form->validate()) {
    $postvars = array('pageTitle', 'pageNavText');
    $data = $Form->receive($postvars);
    $existing = PerchUtil::json_safe_decode($Page->pageAttributes(), true);
    $dynamic_fields = $Form->receive_from_template_fields($Template, $existing, $Pages, $Page);
    $data['pageAttributes'] = PerchUtil::json_safe_encode($dynamic_fields);
    $Page->update($data);
    // log resources
    $Page->log_resources();
    $Alert->set('success', PerchLang::get('Successfully updated'));
    $details = $Page->to_array();
}
 public function get_custom($key = false, $opts = false)
 {
     if ($key === false) {
         return ' ';
     }
     if ($opts === false) {
         return $this->get($key);
     }
     $db = PerchDB::fetch();
     $Perch = Perch::fetch();
     if (isset($opts['page'])) {
         $page = $opts['page'];
     } else {
         $page = $Perch->get_page();
     }
     $where = $this->_get_page_finding_where($page);
     $region_key_for_cache = $key;
     if (is_array($key)) {
         $region_key_for_cache = implode('-', $key);
     }
     if (is_array($page)) {
         $cache_key = implode('|', $page) . ':' . $region_key_for_cache;
     } else {
         $cache_key = $page . ':' . $region_key_for_cache;
     }
     if (array_key_exists($cache_key, $this->custom_region_cache)) {
         $regions = $this->custom_region_cache[$cache_key];
     } else {
         $sql = 'SELECT regionID, regionTemplate, regionPage';
         if ($this->preview) {
             if ($this->preview_rev !== false && $this->preview_contentID != 'all') {
                 $sql .= ', IF(regionID=' . (int) $this->preview_contentID . ', ' . (int) $this->preview_rev . ', regionLatestRev) AS rev';
             } else {
                 $sql .= ', regionLatestRev AS rev';
             }
         } else {
             $sql .= ', regionRev AS rev';
         }
         $sql .= ' FROM ' . $this->table . ' WHERE ';
         if (is_array($key)) {
             $sql .= '(';
             $key_items = array();
             foreach ($key as $k) {
                 $key_items[] = 'regionKey=' . $db->pdb($k);
             }
             $sql .= implode(' OR ', $key_items);
             $sql .= ')';
         } else {
             $sql .= 'regionKey=' . $db->pdb($key);
         }
         $sql .= ' AND (' . implode(' OR ', $where) . ' OR regionPage=' . $db->pdb('*') . ')';
         $regions = $db->get_rows($sql);
         $this->custom_region_cache[$cache_key] = $regions;
     }
     if (!PerchUtil::count($regions)) {
         $str_key = $key;
         if (is_array($key)) {
             $str_key = implode(', ', $key);
         }
         PerchUtil::debug('No matching content regions found. Check region name (' . $str_key . ') and page path options.', 'error');
     }
     $region_path_cache = array();
     if (PerchUtil::count($regions)) {
         foreach ($regions as $region) {
             $region_path_cache[$region['regionID']] = $region['regionPage'];
         }
     }
     $filter_mode = false;
     $content = array();
     // find specific _id
     if (isset($opts['_id'])) {
         $item_id = (int) $opts['_id'];
         $Paging = false;
         $sql = 'SELECT  c.itemID, c.regionID, c.pageID, c.itemJSON FROM ' . PERCH_DB_PREFIX . 'content_items c WHERE c.itemID=' . $this->db->pdb((int) $item_id) . ' ';
         if (PerchUtil::count($regions)) {
             $where = array();
             foreach ($regions as $region) {
                 $where[] = '(c.regionID=' . $this->db->pdb($region['regionID']) . ' AND c.itemRev=' . $this->db->pdb((int) $region['rev']) . ')';
             }
             $sql .= ' AND (' . implode(' OR ', $where) . ')';
         } else {
             $sql .= ' AND c.regionID IS NULL ';
         }
         $sql .= ' LIMIT 1 ';
         $rows = $db->get_rows($sql);
     } 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 .= ' * FROM ( SELECT  idx.itemID, c.regionID, idx.pageID, c.itemJSON, ' . $sortval . ' FROM ' . PERCH_DB_PREFIX . 'content_index idx 
                         JOIN ' . PERCH_DB_PREFIX . 'content_items c ON idx.itemID=c.itemID AND idx.itemRev=c.itemRev AND idx.regionID=c.regionID
                         JOIN ' . PERCH_DB_PREFIX . 'content_index idx2 ON idx.itemID=idx2.itemID AND idx.itemRev=idx2.itemRev  ';
         if (isset($opts['sort'])) {
             $sql .= ' AND idx2.indexKey=' . $db->pdb($opts['sort']) . ' ';
         } else {
             $sql .= ' AND idx2.indexKey=' . $db->pdb('_order') . ' ';
         }
         if (PerchUtil::count($regions)) {
             $where = array();
             foreach ($regions as $region) {
                 $where[] = '(idx.regionID=' . $this->db->pdb((int) $region['regionID']) . ' AND idx.itemRev=' . $this->db->pdb((int) $region['rev']) . ')';
             }
             $where_clause = ' WHERE (' . implode(' OR ', $where) . ')';
         } else {
             $where_clause = ' WHERE idx.regionID IS NULL ';
         }
         $sql .= $where_clause;
         // Categories
         if (isset($opts['category'])) {
             $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_category_sql($pos, false, $match, $where_clause);
                 $sql .= $this->_get_category_sql($neg, true, $match, $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=' . $db->pdb($key) . ' AND idx.indexValue=' . $db->pdb($val) . ')';
                         break;
                     case 'neq':
                     case 'ne':
                     case 'not':
                         $where[] = '(idx.indexKey=' . $db->pdb($key) . ' AND idx.indexValue != ' . $db->pdb($val) . ')';
                         break;
                     case 'gt':
                         $where[] = '(idx.indexKey=' . $db->pdb($key) . ' AND idx.indexValue > ' . $db->pdb($val) . ')';
                         break;
                     case 'gte':
                         $where[] = '(idx.indexKey=' . $db->pdb($key) . ' AND idx.indexValue >= ' . $db->pdb($val) . ')';
                         break;
                     case 'lt':
                         $where[] = '(idx.indexKey=' . $db->pdb($key) . ' AND idx.indexValue < ' . $db->pdb($val) . ')';
                         break;
                     case 'lte':
                         $where[] = '(idx.indexKey=' . $db->pdb($key) . ' AND idx.indexValue <= ' . $db->pdb($val) . ')';
                         break;
                     case 'contains':
                         $v = str_replace('/', '\\/', $val);
                         $where[] = '(idx.indexKey=' . $db->pdb($key) . ' AND idx.indexValue REGEXP ' . $db->pdb('[[:<:]]' . $v . '[[:>:]]') . ')';
                         break;
                     case 'notcontains':
                         $v = str_replace('/', '\\/', $val);
                         $where[] = '(idx.indexKey=' . $db->pdb($key) . ' AND idx.indexValue NOT REGEXP ' . $db->pdb('[[:<:]]' . $v . '[[:>:]]') . ')';
                         break;
                     case 'regex':
                     case 'regexp':
                         $v = str_replace('/', '\\/', $val);
                         $where[] = '(idx.indexKey=' . $db->pdb($key) . ' AND idx.indexValue REGEXP ' . $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=' . $db->pdb($key) . ' AND (idx.indexValue > ' . $db->pdb($vals[0]) . ' AND idx.indexValue < ' . $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=' . $db->pdb($key) . ' AND (idx.indexValue >= ' . $db->pdb($vals[0]) . ' AND idx.indexValue <= ' . $db->pdb($vals[1]) . '))';
                         }
                         break;
                     case 'in':
                     case 'within':
                         $vals = explode(',', $val);
                         if (PerchUtil::count($vals)) {
                             $where[] = '(idx.indexKey=' . $db->pdb($key) . ' AND idx.indexValue IN (' . $db->implode_for_sql_in($vals) . '))';
                         }
                         break;
                 }
             }
             $sql .= ' AND (' . implode($where, ' OR ') . ') ';
         }
         $sql .= ' AND idx.itemID=idx2.itemID AND idx.itemRev=idx2.itemRev
                 ) as tbl GROUP BY itemID, pageID, itemJSON, sortval ';
         // DM added ', pageID, itemJSON, sortval' for MySQL 5.7
         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 (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 = $db->get_rows($sql);
         if (is_object($Paging)) {
             $total_count = $this->db->get_value($Paging->total_count_sql());
             $Paging->set_total($total_count);
         }
     }
     // transform json
     if (PerchUtil::count($rows)) {
         $content = array();
         foreach ($rows as $item) {
             if (trim($item['itemJSON']) != '') {
                 $tmp = PerchUtil::json_safe_decode($item['itemJSON'], true);
                 if (isset($region_path_cache[$item['regionID']])) {
                     $tmp['_page'] = $region_path_cache[$item['regionID']];
                     $tmp['_pageID'] = $item['pageID'];
                 }
                 if (isset($item['sortval'])) {
                     $tmp['_sortvalue'] = $item['sortval'];
                 }
                 // 'each' callback
                 if (isset($opts['each'])) {
                     if (is_callable($opts['each'])) {
                         $tmp = $opts['each']($tmp);
                     }
                 }
                 $content[] = $tmp;
             }
         }
     }
     if (isset($opts['skip-template']) && $opts['skip-template'] == true) {
         if (isset($opts['raw']) && $opts['raw'] == true) {
             if (PerchUtil::count($content)) {
                 foreach ($content as &$item) {
                     if (PerchUtil::count($item)) {
                         foreach ($item as &$field) {
                             if (is_array($field) && isset($field['raw'])) {
                                 $field = $field['raw'];
                             }
                         }
                     }
                 }
             }
             return $content;
         }
     }
     // template
     if (isset($opts['template'])) {
         $template = $opts['template'];
     } else {
         $template = $regions[0]['regionTemplate'];
     }
     $Template = new PerchTemplate('content/' . $template, 'content');
     if (!$Template->file) {
         return 'The template <code>' . PerchUtil::html($template) . '</code> could not be found.';
     }
     // post process
     $processed_vars = array();
     foreach ($content as $item) {
         $tmp = $item;
         if ($tmp) {
             $processed_vars[] = $tmp;
         }
         unset($tmp);
     }
     // Paging to template
     if (is_object($Paging) && $Paging->enabled()) {
         $paging_array = $Paging->to_array($opts);
         // merge in paging vars
         foreach ($processed_vars as &$item) {
             foreach ($paging_array as $key => $val) {
                 $item[$key] = $val;
             }
         }
     }
     if (PerchUtil::count($processed_vars)) {
         if (isset($opts['split-items']) && $opts['split-items']) {
             $html = $Template->render_group($processed_vars, false);
         } else {
             $html = $Template->render_group($processed_vars, true);
         }
     } else {
         $Template->use_noresults();
         $html = $Template->render(array());
     }
     if (isset($opts['skip-template']) && $opts['skip-template'] == true) {
         $out = array();
         if (PerchUtil::count($processed_vars)) {
             $category_field_ids = $Template->find_all_tag_ids('categories');
             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'];
                         }
                     }
                 }
             }
         }
         for ($i = 0; $i < PerchUtil::count($content); $i++) {
             $out[] = array_merge($content[$i], $processed_vars[$i]);
         }
         if (isset($opts['return-html']) && $opts['return-html'] == true) {
             $out['html'] = $html;
         }
         return $out;
     }
     return $html;
 }
 public function register_with_form($SubmittedForm)
 {
     $key = $SubmittedForm->id . (isset($SubmittedForm->form_attributes['type']) ? '.' . $SubmittedForm->form_attributes['type'] : '');
     $Forms = new PerchMembers_Forms($this->api);
     $Form = $Forms->find_or_create($key);
     $do_login = false;
     if (is_object($Form)) {
         $form_settings = PerchUtil::json_safe_decode($Form->formSettings(), true);
         $member = array('memberAuthType' => 'native', 'memberEmail' => '', 'memberPassword' => '', 'memberStatus' => 'pending', 'memberCreated' => date('Y-m-d H:i:s'));
         $data = $SubmittedForm->data;
         $properties = array();
         foreach ($data as $key => $val) {
             if (array_key_exists($key, $this->field_aliases)) {
                 $member[$this->field_aliases[$key]] = $val;
                 $key = $this->field_aliases[$key];
             }
             if (!in_array($key, $this->static_fields)) {
                 $properties[$key] = $val;
             }
         }
         $member['memberProperties'] = PerchUtil::json_safe_encode($properties);
         // Password
         $clear_pwd = $member['memberPassword'];
         if (defined('PERCH_NONPORTABLE_HASHES') && PERCH_NONPORTABLE_HASHES) {
             $portable_hashes = false;
         } else {
             $portable_hashes = true;
         }
         $Hasher = new PasswordHash(8, $portable_hashes);
         $member['memberPassword'] = $Hasher->HashPassword($clear_pwd);
         $Member = $this->create($member);
         $member = array('memberAuthID' => $Member->memberID());
         if (isset($form_settings['moderate']) && $form_settings['moderate'] == '1') {
             if (isset($form_settings['moderator_email'])) {
                 $this->_email_moderator($form_settings['moderator_email'], $Member);
             }
         } else {
             $member['memberStatus'] = 'active';
             $do_login = true;
         }
         $Member->update($member);
         if (isset($form_settings['default_tags']) && $form_settings['default_tags'] != '') {
             $tags = explode(',', $form_settings['default_tags']);
             if (PerchUtil::count($tags)) {
                 foreach ($tags as $tagDisplay) {
                     $expiry = false;
                     if (strpos($tagDisplay, '|') > 0) {
                         $parts = explode('|', $tagDisplay);
                         $tagDisplay = $parts[0];
                         $expiry = $parts[1];
                     }
                     $tagDisplay = trim($tagDisplay);
                     $tag = PerchUtil::urlify($tagDisplay);
                     $Member->add_tag($tag, $tagDisplay, $expiry);
                 }
             }
         }
         if (is_object($Member) && $do_login) {
             $key = base64_encode('login:perch_members:login/login_form.html');
             $data = array('email' => $Member->memberEmail(), 'password' => $clear_pwd, 'pos');
             $files = array();
             $Perch = Perch::fetch();
             $Perch->dispatch_form($key, $data, $files);
         }
         if (is_object($Member) && $clear_pwd === '__auto__') {
             $Member->update(array('memberPassword' => null));
         }
     }
 }
 /**
  * Takes the page, region and field name and gets select box options for the dataselect field type
  * @param  string $regionPage Page path
  * @param  string $regionKey  The name of a region, as used in the page
  * @param  string $fieldID    The title of a field
  * @param  string $valueID    If set, the field to use for values
  * @return array             Options array with label and value keys for select field type.
  */
 public function find_data_select_options($regionPage, $regionKey, $fieldID, $valueID = false)
 {
     $sql = 'SELECT * FROM ' . $this->table . ' 
             WHERE regionPage=' . $this->db->pdb($regionPage) . '
                 AND regionKey=' . $this->db->pdb($regionKey);
     $region = $this->db->get_row($sql);
     if (PerchUtil::count($region)) {
         $Items = new PerchContent_Items();
         $items = $Items->get_for_region($region['regionID'], $region['regionLatestRev']);
         $opts = array();
         if (PerchUtil::count($items)) {
             foreach ($items as $Item) {
                 $details = PerchUtil::json_safe_decode($Item->itemJSON());
                 if (is_object($details)) {
                     $tmp = array();
                     $fieldIDs = explode(' ', $fieldID);
                     $label = array();
                     if (PerchUtil::count($fieldIDs)) {
                         foreach ($fieldIDs as $field) {
                             if ($details->{$field}) {
                                 $label[] = $details->{$field};
                             }
                         }
                     }
                     if ($label) {
                         $tmp['label'] = implode(' ', $label);
                         if ($valueID && $details->{$valueID}) {
                             $tmp['value'] = $details->{$valueID};
                         } else {
                             $tmp['value'] = $tmp['label'];
                         }
                     }
                     if (count($tmp)) {
                         $opts[] = $tmp;
                     }
                 }
             }
         }
         return $opts;
     }
 }
$Form->require_field('addressStreet', 'This field is required');
$Form->require_field('addressPostcode', 'This field is required');
$Form->set_required_fields_from_template($Template, $details);
if ($Form->submitted()) {
    $postvars = ['addressTitle', 'addressBuilding', 'addressStreet', 'addressTown', 'addressRegion', 'addressCountry', 'addressPostcode', 'force'];
    $data = $Form->receive($postvars);
    // Force?
    $force = false;
    if (isset($data['force'])) {
        $force = true;
        unset($data['force']);
    }
    // Dynamic fields
    $previous_values = false;
    if (isset($details['addressDynamicFields'])) {
        $previous_values = PerchUtil::json_safe_decode($details['addressDynamicFields'], true);
    }
    $dynamic_fields = $Form->receive_from_template_fields($Template, $previous_values, $Addresses, $Address);
    $data['addressDynamicFields'] = PerchUtil::json_safe_encode($dynamic_fields);
    // Save
    if (is_object($Address)) {
        $requeue = $Address->shouldQueue($data);
        if (!$force && $requeue) {
            $Tasks->add('address.geocode', $Address->id());
            $data['addressLatitude'] = null;
            $data['addressLongitude'] = null;
        }
        $result = $Address->update($data, $force);
        $details = $Address->to_array();
        $Address->index($Template);
    } else {
 public function post_scheduled_tweets()
 {
     if (!class_exists('tmhOAuth')) {
         require 'tmhOAuth/tmhOAuth.php';
         require 'tmhOAuth/tmhUtilities.php';
     }
     $Tweets = new PerchTwitter_Tweets();
     $tweets = $Tweets->get_scheduled_tweets();
     $sent = 0;
     if (PerchUtil::count($tweets)) {
         $TwitterSettings = new PerchTwitter_Settings();
         $CurrentSettings = $TwitterSettings->find();
         $tmhOAuth = new tmhOAuth(array('consumer_key' => $CurrentSettings->settingTwitterKey(), 'consumer_secret' => $CurrentSettings->settingTwitterSecret(), 'user_token' => $CurrentSettings->settingTwitterToken(), 'user_secret' => $CurrentSettings->settingTwitterTokenSecret()));
         foreach ($tweets as $tweet) {
             $code = $tmhOAuth->request('POST', $tmhOAuth->url('1.1/statuses/update.json'), array('status' => $tweet['tweetStatus']));
             if ($code == 200) {
                 $sent++;
                 $Tweets->mark_scheduled_as_sent($tweet['tweetID']);
             } else {
                 PerchUtil::debug(PerchUtil::json_safe_decode($tmhOAuth->response['response']));
             }
         }
     }
     return $sent;
 }
    $blogID = false;
    $Blog = false;
    $details = array();
}
$Template = $API->get('Template');
$Template->set('blog/blog.html', 'blog');
$Form->handle_empty_block_generation($Template);
$tags = $Template->find_all_tags_and_repeaters();
$Form->require_field('blogTitle', 'Required');
$Form->set_required_fields_from_template($Template, $details);
if ($Form->submitted()) {
    $postvars = array('blogTitle', 'setSlug', 'postTemplate');
    $data = $Form->receive($postvars);
    $prev = false;
    if (isset($details['blogDynamicFields'])) {
        $prev = PerchUtil::json_safe_decode($details['blogDynamicFields'], true);
    }
    $dynamic_fields = $Form->receive_from_template_fields($Template, $prev, $Blogs, $Blog);
    $data['blogDynamicFields'] = PerchUtil::json_safe_encode($dynamic_fields);
    if (!is_object($Blog)) {
        $data['blogSlug'] = PerchUtil::urlify($data['blogTitle']);
        $Blog = $Blogs->create($data);
        PerchUtil::redirect($API->app_path() . '/blogs/edit/?id=' . $Blog->id() . '&created=1');
    }
    $Blog->update($data);
    if (is_object($Blog)) {
        $message = $HTML->success_message('Your blog has been successfully edited. Return to %sblog listing%s', '<a href="' . $API->app_path() . '/blogs">', '</a>');
    } else {
        $message = $HTML->failure_message('Sorry, that blog could not be edited.');
    }
    // clear the caches
Exemple #30
0
 /**
  * Get the individual status using the ID
  *
  * @param string $statusID A Twitter Status ID
  * @return array Assoc array of status details
  * @author Rachel Andrew
  */
 private function get_status($statusID)
 {
     if (!class_exists('tmhOAuth')) {
         require PERCH_PATH . '/addons/apps/perch_twitter/tmhOAuth/tmhOAuth.php';
         require PERCH_PATH . '/addons/apps/perch_twitter/tmhOAuth/tmhUtilities.php';
     }
     if (!class_exists('TwitterSettings')) {
         require PERCH_PATH . '/addons/apps/perch_twitter/PerchTwitter_Settings.class.php';
         require PERCH_PATH . '/addons/apps/perch_twitter/PerchTwitter_Setting.class.php';
     }
     $TwitterSettings = new PerchTwitter_Settings();
     $CurrentSettings = $TwitterSettings->find();
     $tmhOAuth = new tmhOAuth(array('consumer_key' => $CurrentSettings->settingTwitterKey(), 'consumer_secret' => $CurrentSettings->settingTwitterSecret(), 'user_token' => $CurrentSettings->settingTwitterToken(), 'user_secret' => $CurrentSettings->settingTwitterTokenSecret()));
     $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/show.json'), array('id' => $statusID));
     if ($code == 200) {
         $tweet = PerchUtil::json_safe_decode($tmhOAuth->response['response']);
         return $tweet;
     }
     return false;
 }