Example #1
0
function Gdn_ErrorHandler($ErrorNumber, $Message, $File, $Line, $Arguments)
{
    $ErrorReporting = error_reporting();
    // Ignore errors that are below the current error reporting level.
    if (($ErrorReporting & $ErrorNumber) != $ErrorNumber) {
        return FALSE;
    }
    $Backtrace = debug_backtrace();
    if (($ErrorNumber & (E_NOTICE | E_USER_NOTICE)) > 0 & function_exists('Trace')) {
        $Tr = '';
        $i = 0;
        foreach ($Backtrace as $Info) {
            if (!isset($Info['file'])) {
                continue;
            }
            $Tr .= "\n{$Info['file']} line {$Info['line']}.";
            if ($i > 2) {
                break;
            }
            $i++;
        }
        Trace("{$Message}{$Tr}", TRACE_NOTICE);
        return FALSE;
    }
    throw new Gdn_ErrorException($Message, $ErrorNumber, $File, $Line, $Arguments, $Backtrace);
}
Example #2
0
 function TraceErr($AQuery)
 {
     if ($this->_TraceErr) {
         Trace($AQuery);
         //        print '<div class="free" >{'. htmlspecialchars($AQuery, ENT_NOQUOTES). '}</div>';
         //        print '<img src="images/sqltrace.gif" width=24 height=16 title="' . htmlentities($AQuery,ENT_QUOTES) .'">';
     }
 }
 /**
  * We want to re-publish the events
  */
 public function CallEventHandlers($Sender, $EventClassName, $EventName, $EventHandlerType = 'Handler', $Options = [])
 {
     // re-publish
     \Event::fire('forum.event', ['Sender' => $Sender, 'EventClassName' => $EventClassName, 'EventName' => $EventName, 'EventHandlerType' => $EventHandlerType, 'Options' => $Options]);
     // log if we want to
     if (\Config::get('forum::package.trace-include-events', false)) {
         Trace(['EventClassName' => $EventClassName, 'EventName' => $EventName]);
     }
     // defer
     return parent::CallEventHandlers($Sender, $EventClassName, $EventName, $EventHandlerType, $Options);
 }
 public function Query($Sql, $InputParameters = NULL, $Options = [])
 {
     // log if we want to
     if (\Config::get('forum::package.trace-include-queries', false)) {
         Trace(['sql' => $Sql, 'params' => $InputParameters, 'options' => $Options]);
     }
     // defer
     $rc = parent::Query($Sql, $InputParameters, $Options);
     // exception?
     return $rc;
 }
Example #5
0
 public static function GetOrderPropId($code)
 {
     $id = 0;
     if (CModule::IncludeModule('sale')) {
         $db_props = CSaleOrderProps::GetList(array("SORT" => "ASC"), array("CODE" => $code), false, false, array("ID"));
         if ($props = $db_props->Fetch()) {
             $id = $props["ID"];
         }
     } else {
         Trace("Error: can't include module sale");
     }
     return $id;
 }
 public function ToString()
 {
     try {
         $Traces = Trace();
         if (!$Traces) {
             return '';
         }
         $this->SetData('Traces', $Traces);
         return $this->FetchView();
     } catch (Exception $Ex) {
         return $Ex->getMessage();
     }
 }
Example #7
0
 /**
  * Renders attachments.  Checks for error key and if present will display error using WriteErrorAttachment.
  *
  * @param array $Attachment Attachment
  * @return string
  */
 function WriteAttachment($Attachment)
 {
     $customMethod = AttachmentModel::GetWriteAttachmentMethodName($Attachment['Type']);
     if (function_exists($customMethod)) {
         if (GetValue('Error', $Attachment)) {
             WriteErrorAttachment($Attachment);
             return;
         }
         $customMethod($Attachment);
     } else {
         Trace($customMethod, 'Write Attachment method not found');
         Trace($Attachment, 'Attachment');
     }
     return;
 }
Example #8
0
 /**
  * A standard 404 File Not Found error message is delivered when this action
  * is encountered.
  * 
  * @since 2.0.0
  * @access public
  */
 public function FileNotFound()
 {
     $this->RemoveCssFile('admin.css');
     $this->AddCssFile('style.css');
     $this->MasterView = 'default';
     if ($this->Data('ViewPaths')) {
         Trace($this->Data('ViewPaths'), 'View Paths');
     }
     if ($this->DeliveryMethod() == DELIVERY_METHOD_XHTML) {
         header("HTTP/1.0 404", TRUE, 404);
         $this->Render();
     } else {
         $this->RenderException(NotFoundException());
     }
 }
/**
 *
 *
 * @param $ErrorNumber
 * @param $Message
 * @param $File
 * @param $Line
 * @param $Arguments
 * @return bool|void
 * @throws Gdn_ErrorException
 */
function Gdn_ErrorHandler($ErrorNumber, $Message, $File, $Line, $Arguments)
{
    $ErrorReporting = error_reporting();
    // Don't do anything for @supressed errors.
    if ($ErrorReporting === 0) {
        return;
    }
    if (($ErrorReporting & $ErrorNumber) !== $ErrorNumber) {
        if (function_exists('Trace')) {
            Trace("{$Message} in {$File} line {$Line}", TRACE_NOTICE);
        }
        // Ignore errors that are below the current error reporting level.
        return false;
    }
    throw new Gdn_ErrorException($Message, $ErrorNumber, $File, $Line, $Arguments);
}
 /**
  * A standard 404 File Not Found error message is delivered when this action
  * is encountered.
  *
  * @since 2.0.0
  * @access public
  */
 public function FileNotFound()
 {
     $this->RemoveCssFile('admin.css');
     $this->AddCssFile('style.css');
     $this->MasterView = 'default';
     $this->CssClass = 'SplashMessage NoPanel';
     if ($this->Data('ViewPaths')) {
         Trace($this->Data('ViewPaths'), 'View Paths');
     }
     $this->SetData('_NoMessages', TRUE);
     Gdn_Theme::Section('Error');
     if ($this->DeliveryMethod() == DELIVERY_METHOD_XHTML) {
         safeHeader("HTTP/1.0 404", TRUE, 404);
         $this->Render();
     } else {
         $this->RenderException(NotFoundException());
     }
 }
 public function API($Path, $Post = FALSE)
 {
     // Build the url.
     $Url = 'https://graph.facebook.com/' . ltrim($Path, '/');
     $AccessToken = $this->AccessToken();
     if (!$AccessToken) {
         throw new Gdn_UserException("You don't have a valid Facebook connection.");
     }
     if (strpos($Url, '?') === false) {
         $Url .= '?';
     } else {
         $Url .= '&';
     }
     $Url .= 'access_token=' . urlencode($AccessToken);
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_HEADER, false);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_URL, $Url);
     if ($Post !== false) {
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $Post);
         Trace("  POST {$Url}");
     } else {
         Trace("  GET  {$Url}");
     }
     $Response = curl_exec($ch);
     $HttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     $ContentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
     curl_close($ch);
     Gdn::Controller()->SetJson('Type', $ContentType);
     if (strpos($ContentType, 'javascript') !== FALSE) {
         $Result = json_decode($Response, TRUE);
         if (isset($Result['error'])) {
             Gdn::Dispatcher()->PassData('FacebookResponse', $Result);
             throw new Gdn_UserException($Result['error']['message']);
         }
     } else {
         $Result = $Response;
     }
     return $Result;
 }
function GetTimeStampFromLogFile($file_name)
{
    $cmd = "tail {$file_name}";
    exec($cmd, $logs_arr);
    $arr_len = count($logs_arr);
    var_dump($logs_arr);
    for ($i = $arr_len - 1; $i >= 0; --$i) {
        if (strncmp($logs_arr[$i], '201', 3) == 0) {
            // log "2011-12-06 15:54:21 "
            Trace("find a log :" . $logs_arr[$i]);
            $str = str_replace('-', '', $logs_arr[$i]);
            $str = str_replace(' ', '', $str);
            $str = str_replace('\\t', '', $str);
            $str = str_replace(':', '', $str);
            $str = substr($str, 0, 14);
            Trace("log time stamp: {$str}");
            return MktimeFromString($str);
        }
    }
    SendWarningEMail(__FUNCTION__ . " ERROR. The monitor script working abnormal, please check it!", __FILE__ . " work abnormal");
    Trace(__FUNCTION__ . ' Error!!');
    return time();
}
Example #13
0
function ProcessDBFRecord($ASurgeryID, $ACaseID, $ADate, $ASend, $AError)
{
    $vDB = GetDB();
    if (empty($ASurgeryID)) {
        $vSurgery = $vDB->Get('emst_surgeries', '*', $vDB->CondEqual('case_id', $ACaseID) . ' AND DATE(`date`)=' . $vDB->Decorate($ADate));
    } else {
        $vSurgery = $vDB->Get('emst_surgeries', '*', $vDB->CondEqual('id', $ASurgeryID));
    }
    if (is_array($vSurgery)) {
        if ($ASend === '1' || $ASend === '0' && $AError == 'Повторная запись') {
            $vUpdate = array('eisoms_status' => '2', 'eisoms_message' => '');
            $vDB->UpdateById('emst_surgeries', $vSurgery['id'], $vUpdate);
        } else {
            if ($ASend === '0' && $AError != '') {
                $vUpdate = array('eisoms_status' => '1', 'eisoms_message' => $AError);
                $vDB->UpdateById('emst_surgeries', $vSurgery['id'], $vUpdate);
            } else {
                Trace("Can't update ProcessDBFRecord({$ASurgeryID}, {$ACaseID}, {$ADate}, {$ASend}, {$AError})");
            }
        }
    } else {
        Trace("Can't find ProcessDBFRecord({$ASurgeryID}, {$ACaseID}, {$ADate}, {$ASend}, {$AError})");
    }
}
Example #14
0
 /**
  * Get the path of a view.
  *
  * @param string $View The name of the view.
  * @param string $Controller The name of the controller invoking the view or blank.
  * @param string $Folder The application folder or plugins/plugin folder.
  * @return string|false The path to the view or false if it wasn't found.
  * @deprecated
  */
 function viewLocation($View, $Controller, $Folder)
 {
     deprecated('viewLocation()');
     $Paths = array();
     if (strpos($View, '/') !== false) {
         // This is a path to the view from the root.
         $Paths[] = $View;
     } else {
         $View = strtolower($View);
         $Controller = strtolower(StringEndsWith($Controller, 'Controller', true, true));
         if ($Controller) {
             $Controller = '/' . $Controller;
         }
         $Extensions = array('tpl', 'php');
         // 1. First we check the theme.
         if (Gdn::Controller() && ($Theme = Gdn::Controller()->Theme)) {
             foreach ($Extensions as $Ext) {
                 $Paths[] = PATH_THEMES . "/{$Theme}/views{$Controller}/{$View}.{$Ext}";
             }
         }
         // 2. Then we check the application/plugin.
         if (StringBeginsWith($Folder, 'plugins/')) {
             // This is a plugin view.
             foreach ($Extensions as $Ext) {
                 $Paths[] = PATH_ROOT . "/{$Folder}/views{$Controller}/{$View}.{$Ext}";
             }
         } else {
             // This is an application view.
             $Folder = strtolower($Folder);
             foreach ($Extensions as $Ext) {
                 $Paths[] = PATH_APPLICATIONS . "/{$Folder}/views{$Controller}/{$View}.{$Ext}";
             }
             if ($Folder != 'dashboard' && StringEndsWith($View, '.master')) {
                 // This is a master view that can always fall back to the dashboard.
                 foreach ($Extensions as $Ext) {
                     $Paths[] = PATH_APPLICATIONS . "/dashboard/views{$Controller}/{$View}.{$Ext}";
                 }
             }
         }
     }
     // Now let's search the paths for the view.
     foreach ($Paths as $Path) {
         if (file_exists($Path)) {
             return $Path;
         }
     }
     Trace(array('view' => $View, 'controller' => $Controller, 'folder' => $Folder), 'View');
     Trace($Paths, 'ViewLocation()');
     return false;
 }
Example #15
0
 /**
  * Save an image from a field and delete any old image that's been uploaded.
  *
  * @param string $Field The name of the field. The image will be uploaded with the _New extension while the current image will be just the field name.
  * @param array $Options
  */
 public function saveImage($Field, $Options = array())
 {
     $Upload = new Gdn_UploadImage();
     $FileField = str_replace('.', '_', $Field);
     if (!getValueR("{$FileField}_New.name", $_FILES)) {
         trace("{$Field} not uploaded, returning.");
         return false;
     }
     // First make sure the file is valid.
     try {
         $TmpName = $Upload->validateUpload($FileField . '_New', true);
         if (!$TmpName) {
             return false;
             // no file uploaded.
         }
     } catch (Exception $Ex) {
         $this->addError($Ex);
         return false;
     }
     // Get the file extension of the file.
     $Ext = val('OutputType', $Options, trim($Upload->getUploadedFileExtension(), '.'));
     if ($Ext == 'jpeg') {
         $Ext = 'jpg';
     }
     Trace($Ext, 'Ext');
     // The file is valid so let's come up with its new name.
     if (isset($Options['Name'])) {
         $Name = $Options['Name'];
     } elseif (isset($Options['Prefix'])) {
         $Name = $Options['Prefix'] . md5(microtime()) . '.' . $Ext;
     } else {
         $Name = md5(microtime()) . '.' . $Ext;
     }
     // We need to parse out the size.
     $Size = val('Size', $Options);
     if ($Size) {
         if (is_numeric($Size)) {
             touchValue('Width', $Options, $Size);
             touchValue('Height', $Options, $Size);
         } elseif (preg_match('`(\\d+)x(\\d+)`i', $Size, $M)) {
             touchValue('Width', $Options, $M[1]);
             touchValue('Height', $Options, $M[2]);
         }
     }
     trace($Options, "Saving image {$Name}.");
     try {
         $Parsed = $Upload->saveImageAs($TmpName, $Name, val('Height', $Options, ''), val('Width', $Options, ''), $Options);
         trace($Parsed, 'Saved Image');
         $Current = $this->getFormValue($Field);
         if ($Current && val('DeleteOriginal', $Options, true)) {
             // Delete the current image.
             trace("Deleting original image: {$Current}.");
             if ($Current) {
                 $Upload->delete($Current);
             }
         }
         // Set the current value.
         $this->setFormValue($Field, $Parsed['SaveName']);
     } catch (Exception $Ex) {
         $this->addError($Ex);
     }
 }
Example #16
0
 public function Save($Data, $Preference = FALSE, $Options = array())
 {
     Trace('ActivityModel->Save()');
     $Activity = $Data;
     $this->_Touch($Activity);
     if ($Activity['ActivityUserID'] == $Activity['NotifyUserID'] && !GetValue('Force', $Options)) {
         Trace('Skipping activity because it would notify the user of something they did.');
         return;
         // don't notify users of something they did.
     }
     // Check the user's preference.
     if ($Preference) {
         list($Popup, $Email) = self::NotificationPreference($Preference, $Activity['NotifyUserID'], 'both');
         if ($Popup && !$Activity['Notified']) {
             $Activity['Notified'] = self::SENT_PENDING;
         }
         if ($Email && !$Activity['Emailed']) {
             $Activity['Emailed'] = self::SENT_PENDING;
         }
         if (!$Activity['Notified'] && !$Activity['Emailed'] && !GetValue('Force', $Options)) {
             Trace("Skipping activity because the user has no preference set.");
             return;
         }
     }
     $ActivityType = self::GetActivityType($Activity['ActivityType']);
     $ActivityTypeID = ArrayValue('ActivityTypeID', $ActivityType);
     if (!$ActivityTypeID) {
         Trace("There is no {$ActivityType} activity type.", TRACE_WARNING);
         $ActivityType = self::GetActivityType('Default');
         $ActivityTypeID = ArrayValue('ActivityTypeID', $ActivityType);
     }
     $Activity['ActivityTypeID'] = $ActivityTypeID;
     $NotificationInc = 0;
     if ($Activity['NotifyUserID'] > 0 && $Activity['Notified']) {
         $NotificationInc = 1;
     }
     // Check to see if we are sharing this activity with another one.
     if ($CommentActivityID = GetValue('CommentActivityID', $Activity['Data'])) {
         $CommentActivity = $this->GetID($CommentActivityID);
         $Activity['Data']['CommentNotifyUserID'] = $CommentActivity['NotifyUserID'];
     }
     // Make sure this activity isn't a duplicate.
     if (GetValue('CheckRecord', $Options)) {
         // Check to see if this record already notified so we don't notify multiple times.
         $Where = ArrayTranslate($Activity, array('NotifyUserID', 'RecordType', 'RecordID'));
         $Where['DateUpdated >'] = Gdn_Format::ToDateTime(strtotime('-2 days'));
         // index hint
         $CheckActivity = $this->SQL->GetWhere('Activity', $Where)->FirstRow();
         if ($CheckActivity) {
             return FALSE;
         }
     }
     // Check to share the activity.
     if (GetValue('Share', $Options)) {
         $this->Share($Activity);
     }
     // Group he activity.
     if ($GroupBy = GetValue('GroupBy', $Options)) {
         $GroupBy = (array) $GroupBy;
         $Where = array();
         foreach ($GroupBy as $ColumnName) {
             $Where[$ColumnName] = $Activity[$ColumnName];
         }
         $Where['NotifyUserID'] = $Activity['NotifyUserID'];
         // Make sure to only group activities by day.
         $Where['DateInserted >'] = Gdn_Format::ToDateTime(strtotime('-1 day'));
         // See if there is another activity to group these into.
         $GroupActivity = $this->SQL->GetWhere('Activity', $Where)->FirstRow(DATASET_TYPE_ARRAY);
         if ($GroupActivity) {
             $GroupActivity['Data'] = @unserialize($GroupActivity['Data']);
             $Activity = $this->MergeActivities($GroupActivity, $Activity);
             $NotificationInc = 0;
         }
     }
     $Delete = FALSE;
     if ($Activity['Emailed'] == self::SENT_PENDING) {
         $this->Email($Activity);
         $Delete = GetValue('_Delete', $Activity);
     }
     $ActivityData = $Activity['Data'];
     if (isset($Activity['Data']) && is_array($Activity['Data'])) {
         $Activity['Data'] = serialize($Activity['Data']);
     }
     $this->DefineSchema();
     $Activity = $this->FilterSchema($Activity);
     $ActivityID = GetValue('ActivityID', $Activity);
     if (!$ActivityID) {
         if (!$Delete) {
             $this->AddInsertFields($Activity);
             TouchValue('DateUpdated', $Activity, $Activity['DateInserted']);
             $this->EventArguments['Activity'] =& $Activity;
             $this->EventArguments['ActivityID'] = NULL;
             $this->FireEvent('BeforeSave');
             if (count($this->ValidationResults()) > 0) {
                 return FALSE;
             }
             if (GetValue('CheckSpam', $Options)) {
                 // Check for spam
                 $Spam = SpamModel::IsSpam('Activity', $Activity);
                 if ($Spam) {
                     return SPAM;
                 }
                 // Check for approval
                 $ApprovalRequired = CheckRestriction('Vanilla.Approval.Require');
                 if ($ApprovalRequired && !GetValue('Verified', Gdn::Session()->User)) {
                     LogModel::Insert('Pending', 'Activity', $Activity);
                     return UNAPPROVED;
                 }
             }
             $ActivityID = $this->SQL->Insert('Activity', $Activity);
             $Activity['ActivityID'] = $ActivityID;
         }
     } else {
         $Activity['DateUpdated'] = Gdn_Format::ToDateTime();
         unset($Activity['ActivityID']);
         $this->EventArguments['Activity'] =& $Activity;
         $this->EventArguments['ActivityID'] = $ActivityID;
         $this->FireEvent('BeforeSave');
         if (count($this->ValidationResults()) > 0) {
             return FALSE;
         }
         $this->SQL->Put('Activity', $Activity, array('ActivityID' => $ActivityID));
         $Activity['ActivityID'] = $ActivityID;
     }
     $Activity['Data'] = $ActivityData;
     if (isset($CommentActivity)) {
         $CommentActivity['Data']['SharedActivityID'] = $Activity['ActivityID'];
         $CommentActivity['Data']['SharedNotifyUserID'] = $Activity['NotifyUserID'];
         $this->SetField($CommentActivity['ActivityID'], 'Data', $CommentActivity['Data']);
     }
     if ($NotificationInc > 0) {
         $CountNotifications = Gdn::UserModel()->GetID($Activity['NotifyUserID'])->CountNotifications + $NotificationInc;
         Gdn::UserModel()->SetField($Activity['NotifyUserID'], 'CountNotifications', $CountNotifications);
     }
     return $Activity;
 }
Example #17
0
function TraceVar($varName)
{
    Trace("{$varName} = [" . $GLOBALS[$varName] . "]");
}
 /**
  * Undocumented method.
  *
  * @todo Method RenderMaster() needs a description.
  */
 public function RenderMaster()
 {
     // Build the master view if necessary
     if (in_array($this->_DeliveryType, array(DELIVERY_TYPE_ALL))) {
         $this->MasterView = $this->MasterView();
         // Only get css & ui components if this is NOT a syndication request
         if ($this->SyndicationMethod == SYNDICATION_NONE && is_object($this->Head)) {
             //            if (ArrayHasValue($this->_CssFiles, 'style.css')) {
             //               $this->AddCssFile('custom.css');
             //
             //               // Add the theme option's css file.
             //               if ($this->Theme && $this->ThemeOptions) {
             //                  $Filenames = GetValueR('Styles.Value', $this->ThemeOptions);
             //                  if (is_string($Filenames) && $Filenames != '%s')
             //                     $this->_CssFiles[] = array('FileName' => ChangeBasename('custom.css', $Filenames), 'AppFolder' => FALSE, 'Options' => FALSE);
             //               }
             //            } elseif (ArrayHasValue($this->_CssFiles, 'admin.css')) {
             //               $this->AddCssFile('customadmin.css');
             //            }
             $this->EventArguments['CssFiles'] =& $this->_CssFiles;
             $this->FireEvent('BeforeAddCss');
             $ETag = AssetModel::ETag();
             $CombineAssets = C('Garden.CombineAssets');
             $ThemeType = IsMobile() ? 'mobile' : 'desktop';
             // And now search for/add all css files.
             foreach ($this->_CssFiles as $CssInfo) {
                 $CssFile = $CssInfo['FileName'];
                 // style.css and admin.css deserve some custom processing.
                 if (in_array($CssFile, array('style.css', 'admin.css'))) {
                     if (!$CombineAssets) {
                         // Grab all of the css files from the asset model.
                         $AssetModel = new AssetModel();
                         $CssFiles = $AssetModel->GetCssFiles($ThemeType, ucfirst(substr($CssFile, 0, -4)), $ETag);
                         foreach ($CssFiles as $Info) {
                             $this->Head->AddCss($Info[1], 'all', TRUE, $CssInfo);
                         }
                     } else {
                         $Basename = substr($CssFile, 0, -4);
                         $this->Head->AddCss(Url("/utility/css/{$ThemeType}/{$Basename}-{$ETag}.css", '//'), 'all', FALSE, $CssInfo['Options']);
                     }
                     continue;
                 }
                 if (StringBeginsWith($CssFile, 'http')) {
                     $this->Head->AddCss($CssFile, 'all', GetValue('AddVersion', $CssInfo, TRUE), $CssInfo['Options']);
                     continue;
                 } elseif (strpos($CssFile, '/') !== FALSE) {
                     // A direct path to the file was given.
                     $CssPaths = array(CombinePaths(array(PATH_ROOT, str_replace('/', DS, $CssFile))));
                 } else {
                     //                  $CssGlob = preg_replace('/(.*)(\.css)/', '\1*\2', $CssFile);
                     $AppFolder = $CssInfo['AppFolder'];
                     if ($AppFolder == '') {
                         $AppFolder = $this->ApplicationFolder;
                     }
                     // CSS comes from one of four places:
                     $CssPaths = array();
                     if ($this->Theme) {
                         // Use the default filename.
                         $CssPaths[] = PATH_THEMES . DS . $this->Theme . DS . 'design' . DS . $CssFile;
                     }
                     // 3. Application or plugin.
                     if (StringBeginsWith($AppFolder, 'plugins/')) {
                         // The css is coming from a plugin.
                         $AppFolder = substr($AppFolder, strlen('plugins/'));
                         $CssPaths[] = PATH_PLUGINS . "/{$AppFolder}/design/{$CssFile}";
                         $CssPaths[] = PATH_PLUGINS . "/{$AppFolder}/{$CssFile}";
                     } elseif (in_array($AppFolder, array('static', 'resources'))) {
                         // This is a static css file.
                         $CssPaths[] = PATH_ROOT . "/resources/css/{$CssFile}";
                     } else {
                         // Application default. eg. root/applications/app_name/design/
                         $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile;
                     }
                     // 4. Garden default. eg. root/applications/dashboard/design/
                     $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile;
                 }
                 // Find the first file that matches the path.
                 $CssPath = FALSE;
                 foreach ($CssPaths as $Glob) {
                     $Paths = SafeGlob($Glob);
                     if (is_array($Paths) && count($Paths) > 0) {
                         $CssPath = $Paths[0];
                         break;
                     }
                 }
                 // Check to see if there is a CSS cacher.
                 $CssCacher = Gdn::Factory('CssCacher');
                 if (!is_null($CssCacher)) {
                     $CssPath = $CssCacher->Get($CssPath, $AppFolder);
                 }
                 if ($CssPath !== FALSE) {
                     $CssPath = substr($CssPath, strlen(PATH_ROOT));
                     $CssPath = str_replace(DS, '/', $CssPath);
                     $this->Head->AddCss($CssPath, 'all', TRUE, $CssInfo['Options']);
                 }
             }
             // Add a custom js file.
             if (ArrayHasValue($this->_CssFiles, 'style.css')) {
                 $this->AddJsFile('custom.js');
             }
             // only to non-admin pages.
             // And now search for/add all JS files.
             $Cdns = array();
             if (Gdn::Request()->Scheme() != 'https' && !C('Garden.Cdns.Disable', FALSE)) {
                 $Cdns = array('jquery.js' => 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js');
             }
             $this->EventArguments['Cdns'] =& $Cdns;
             $this->FireEvent('AfterJsCdns');
             foreach ($this->_JsFiles as $Index => $JsInfo) {
                 $JsFile = $JsInfo['FileName'];
                 if (isset($Cdns[$JsFile])) {
                     $JsFile = $Cdns[$JsFile];
                 }
                 if (strpos($JsFile, '//') !== FALSE) {
                     // This is a link to an external file.
                     $this->Head->AddScript($JsFile, 'text/javascript', GetValue('Options', $JsInfo, array()));
                     continue;
                 } elseif (strpos($JsFile, '/') !== FALSE) {
                     // A direct path to the file was given.
                     $JsPaths = array(CombinePaths(array(PATH_ROOT, str_replace('/', DS, $JsFile)), DS));
                 } else {
                     $AppFolder = $JsInfo['AppFolder'];
                     if ($AppFolder == '') {
                         $AppFolder = $this->ApplicationFolder;
                     }
                     // JS can come from a theme, an any of the application folder, or it can come from the global js folder:
                     $JsPaths = array();
                     if ($this->Theme) {
                         // 1. Application-specific js. eg. root/themes/theme_name/app_name/design/
                         $JsPaths[] = PATH_THEMES . DS . $this->Theme . DS . $AppFolder . DS . 'js' . DS . $JsFile;
                         // 2. Garden-wide theme view. eg. root/themes/theme_name/design/
                         $JsPaths[] = PATH_THEMES . DS . $this->Theme . DS . 'js' . DS . $JsFile;
                     }
                     // 3. The application or plugin folder.
                     if (StringBeginsWith(trim($AppFolder, '/'), 'plugins/')) {
                         $JsPaths[] = PATH_PLUGINS . strstr($AppFolder, '/') . "/js/{$JsFile}";
                         $JsPaths[] = PATH_PLUGINS . strstr($AppFolder, '/') . "/{$JsFile}";
                     } else {
                         $JsPaths[] = PATH_APPLICATIONS . "/{$AppFolder}/js/{$JsFile}";
                     }
                     // 4. Global JS folder. eg. root/js/
                     $JsPaths[] = PATH_ROOT . DS . 'js' . DS . $JsFile;
                     // 5. Global JS library folder. eg. root/js/library/
                     $JsPaths[] = PATH_ROOT . DS . 'js' . DS . 'library' . DS . $JsFile;
                 }
                 // Find the first file that matches the path.
                 $JsPath = FALSE;
                 foreach ($JsPaths as $Glob) {
                     $Paths = SafeGlob($Glob);
                     if (is_array($Paths) && count($Paths) > 0) {
                         $JsPath = $Paths[0];
                         break;
                     }
                 }
                 if ($JsPath !== FALSE) {
                     $JsSrc = str_replace(array(PATH_ROOT, DS), array('', '/'), $JsPath);
                     $Options = (array) $JsInfo['Options'];
                     $Options['path'] = $JsPath;
                     $Version = GetValue('Version', $JsInfo);
                     if ($Version) {
                         TouchValue('version', $Options, $Version);
                     }
                     $this->Head->AddScript($JsSrc, 'text/javascript', $Options);
                 }
             }
         }
         // Add the favicon.
         $Favicon = C('Garden.FavIcon');
         if ($Favicon) {
             $this->Head->SetFavIcon(Gdn_Upload::Url($Favicon));
         }
         // Make sure the head module gets passed into the assets collection.
         $this->AddModule('Head');
     }
     // Master views come from one of four places:
     $MasterViewPaths = array();
     $MasterViewPath2 = ViewLocation($this->MasterView() . '.master', '', $this->ApplicationFolder);
     if (strpos($this->MasterView, '/') !== FALSE) {
         $MasterViewPaths[] = CombinePaths(array(PATH_ROOT, str_replace('/', DS, $this->MasterView) . '.master*'));
     } else {
         if ($this->Theme) {
             // 1. Application-specific theme view. eg. root/themes/theme_name/app_name/views/
             $MasterViewPaths[] = CombinePaths(array(PATH_THEMES, $this->Theme, $this->ApplicationFolder, 'views', $this->MasterView . '.master*'));
             // 2. Garden-wide theme view. eg. /path/to/application/themes/theme_name/views/
             $MasterViewPaths[] = CombinePaths(array(PATH_THEMES, $this->Theme, 'views', $this->MasterView . '.master*'));
         }
         // 3. Application default. eg. root/app_name/views/
         $MasterViewPaths[] = CombinePaths(array(PATH_APPLICATIONS, $this->ApplicationFolder, 'views', $this->MasterView . '.master*'));
         // 4. Garden default. eg. root/dashboard/views/
         $MasterViewPaths[] = CombinePaths(array(PATH_APPLICATIONS, 'dashboard', 'views', $this->MasterView . '.master*'));
     }
     // Find the first file that matches the path.
     $MasterViewPath = FALSE;
     foreach ($MasterViewPaths as $Glob) {
         $Paths = SafeGlob($Glob);
         if (is_array($Paths) && count($Paths) > 0) {
             $MasterViewPath = $Paths[0];
             break;
         }
     }
     if ($MasterViewPath != $MasterViewPath2) {
         Trace("Master views differ. Controller: {$MasterViewPath}, ViewLocation(): {$MasterViewPath2}", TRACE_WARNING);
     }
     $this->EventArguments['MasterViewPath'] =& $MasterViewPath;
     $this->FireEvent('BeforeFetchMaster');
     if ($MasterViewPath === FALSE) {
         trigger_error(ErrorMessage("Could not find master view: {$this->MasterView}.master*", $this->ClassName, '_FetchController'), E_USER_ERROR);
     }
     /// A unique identifier that can be used in the body tag of the master view if needed.
     $ControllerName = $this->ClassName;
     // Strip "Controller" from the body identifier.
     if (substr($ControllerName, -10) == 'Controller') {
         $ControllerName = substr($ControllerName, 0, -10);
     }
     // Strip "Gdn_" from the body identifier.
     if (substr($ControllerName, 0, 4) == 'Gdn_') {
         $ControllerName = substr($ControllerName, 4);
     }
     $this->SetData('CssClass', $this->Application . ' ' . $ControllerName . ' ' . $this->RequestMethod . ' ' . $this->CssClass, TRUE);
     // Check to see if there is a handler for this particular extension.
     $ViewHandler = Gdn::Factory('ViewHandler' . strtolower(strrchr($MasterViewPath, '.')));
     if (is_null($ViewHandler)) {
         $BodyIdentifier = strtolower($this->ApplicationFolder . '_' . $ControllerName . '_' . Gdn_Format::AlphaNumeric(strtolower($this->RequestMethod)));
         include $MasterViewPath;
     } else {
         $ViewHandler->Render($MasterViewPath, $this);
     }
 }
 public function NewUserRoleIDs()
 {
     // Registration method
     $RegistrationMethod = C('Garden.Registration.Method', 'Captcha');
     $DefaultRoleID = C('Garden.Registration.DefaultRoles');
     switch ($RegistrationMethod) {
         case 'Approval':
             $RoleID = C('Garden.Registration.ApplicantRoleID', $DefaultRoleID);
             break;
         case 'Invitation':
             throw new Gdn_UserException(T('This forum is currently set to invitation only mode.'));
             break;
         case 'Basic':
         case 'Captcha':
         default:
             $RoleID = $DefaultRoleID;
             break;
     }
     if (empty($RoleID)) {
         Trace("You don't have any default roles defined.", TRACE_WARNING);
     }
     return $RoleID;
 }
 public function Trace($Message, $Type = TRACE_INFO)
 {
     if ($this->Trace) {
         Trace($Message, $Type);
     }
 }
Example #21
0
 public function API($Url, $Params = NULL, $Method = 'GET')
 {
     if (strpos($Url, '//') === FALSE) {
         $Url = self::$BaseApiUrl . trim($Url, '/');
     }
     $Consumer = new OAuthConsumer(C('Plugins.Twitter.ConsumerKey'), C('Plugins.Twitter.Secret'));
     if ($Method == 'POST') {
         $Post = $Params;
     } else {
         $Post = NULL;
     }
     $AccessToken = $this->AccessToken();
     //      var_dump($AccessToken);
     $Request = OAuthRequest::from_consumer_and_token($Consumer, $AccessToken, $Method, $Url, $Params);
     $SignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
     $Request->sign_request($SignatureMethod, $Consumer, $AccessToken);
     //      print_r($Params);
     $Curl = $this->_Curl($Request, $Post);
     curl_setopt($Curl, CURLINFO_HEADER_OUT, TRUE);
     //      curl_setopt($Curl, CURLOPT_VERBOSE, TRUE);
     //      $fp = fopen("php://stdout", 'w');
     //      curl_setopt($Curl, CURLOPT_STDERR, $fp);
     $Response = curl_exec($Curl);
     $HttpCode = curl_getinfo($Curl, CURLINFO_HTTP_CODE);
     if ($Response == FALSE) {
         $Response = curl_error($Curl);
     }
     //      echo curl_getinfo($Curl, CURLINFO_HEADER_OUT);
     //
     //      echo($Request->to_postdata());
     //      echo "\n\n";
     Trace(curl_getinfo($Curl, CURLINFO_HEADER_OUT));
     Trace($Response, 'Response');
     //      print_r(curl_getinfo($Curl));
     //      die();
     curl_close($Curl);
     Gdn::Controller()->SetJson('Response', $Response);
     if (strpos($Url, '.json') !== FALSE) {
         $Result = @json_decode($Response, TRUE) or $Response;
     } else {
         $Result = $Response;
     }
     //      print_r($Result);
     if ($HttpCode == '200') {
         return $Result;
     } else {
         throw new Gdn_UserException(GetValueR('errors.0.message', $Result, $Response), $HttpCode);
     }
 }
Example #22
0
?>


        <?php 
$intSectionID = $APPLICATION->IncludeComponent("bitrix:catalog.section", $sectionTemplate, array("IBLOCK_TYPE" => $arParams["IBLOCK_TYPE"], "IBLOCK_ID" => $arParams["IBLOCK_ID"], "ELEMENT_SORT_FIELD" => $sort, "ELEMENT_SORT_ORDER" => $sortOrder, "ELEMENT_SORT_FIELD2" => $sort2, "ELEMENT_SORT_ORDER2" => $sortOrder2, "PROPERTY_CODE" => $arParams["LIST_PROPERTY_CODE"], "META_KEYWORDS" => $arParams["LIST_META_KEYWORDS"], "META_DESCRIPTION" => $arParams["LIST_META_DESCRIPTION"], "BROWSER_TITLE" => $arParams["LIST_BROWSER_TITLE"], "INCLUDE_SUBSECTIONS" => $arParams["INCLUDE_SUBSECTIONS"], "BASKET_URL" => $arParams["BASKET_URL"], "ACTION_VARIABLE" => $arParams["ACTION_VARIABLE"], "PRODUCT_ID_VARIABLE" => $arParams["PRODUCT_ID_VARIABLE"], "SECTION_ID_VARIABLE" => $arParams["SECTION_ID_VARIABLE"], "PRODUCT_QUANTITY_VARIABLE" => $arParams["PRODUCT_QUANTITY_VARIABLE"], "PRODUCT_PROPS_VARIABLE" => $arParams["PRODUCT_PROPS_VARIABLE"], "FILTER_NAME" => $arParams["FILTER_NAME"], "CACHE_TYPE" => $arParams["CACHE_TYPE"], "CACHE_TIME" => $arParams["CACHE_TIME"], "CACHE_FILTER" => $arParams["CACHE_FILTER"], "CACHE_GROUPS" => $arParams["CACHE_GROUPS"], "SET_TITLE" => $arParams["SET_TITLE"], "SET_STATUS_404" => $arParams["SET_STATUS_404"], "DISPLAY_COMPARE" => $arParams["USE_COMPARE"], "PAGE_ELEMENT_COUNT" => $arParams["PAGE_ELEMENT_COUNT"], "LINE_ELEMENT_COUNT" => $arParams["LINE_ELEMENT_COUNT"], "PRICE_CODE" => $arParams["PRICE_CODE"], "USE_PRICE_COUNT" => $arParams["USE_PRICE_COUNT"], "SHOW_PRICE_COUNT" => $arParams["SHOW_PRICE_COUNT"], "PRICE_VAT_INCLUDE" => $arParams["PRICE_VAT_INCLUDE"], "USE_PRODUCT_QUANTITY" => $arParams['USE_PRODUCT_QUANTITY'], "ADD_PROPERTIES_TO_BASKET" => isset($arParams["ADD_PROPERTIES_TO_BASKET"]) ? $arParams["ADD_PROPERTIES_TO_BASKET"] : '', "PARTIAL_PRODUCT_PROPERTIES" => isset($arParams["PARTIAL_PRODUCT_PROPERTIES"]) ? $arParams["PARTIAL_PRODUCT_PROPERTIES"] : '', "PRODUCT_PROPERTIES" => $arParams["PRODUCT_PROPERTIES"], "DISPLAY_TOP_PAGER" => $arParams["DISPLAY_TOP_PAGER"], "DISPLAY_BOTTOM_PAGER" => $arParams["DISPLAY_BOTTOM_PAGER"], "PAGER_TITLE" => $arParams["PAGER_TITLE"], "PAGER_SHOW_ALWAYS" => $arParams["PAGER_SHOW_ALWAYS"], "PAGER_TEMPLATE" => $arParams["PAGER_TEMPLATE"], "PAGER_DESC_NUMBERING" => $arParams["PAGER_DESC_NUMBERING"], "PAGER_DESC_NUMBERING_CACHE_TIME" => $arParams["PAGER_DESC_NUMBERING_CACHE_TIME"], "PAGER_SHOW_ALL" => $arParams["PAGER_SHOW_ALL"], "OFFERS_CART_PROPERTIES" => $arParams["OFFERS_CART_PROPERTIES"], "OFFERS_FIELD_CODE" => $arParams["LIST_OFFERS_FIELD_CODE"], "OFFERS_PROPERTY_CODE" => $arParams["LIST_OFFERS_PROPERTY_CODE"], "OFFERS_SORT_FIELD" => $arParams["OFFERS_SORT_FIELD"], "OFFERS_SORT_ORDER" => $arParams["OFFERS_SORT_ORDER"], "OFFERS_SORT_FIELD2" => $arParams["OFFERS_SORT_FIELD2"], "OFFERS_SORT_ORDER2" => $arParams["OFFERS_SORT_ORDER2"], "OFFERS_LIMIT" => $arParams["LIST_OFFERS_LIMIT"], "SECTION_ID" => $arResult["VARIABLES"]["SECTION_ID"], "SECTION_CODE" => $arResult["VARIABLES"]["SECTION_CODE"], "SECTION_URL" => $arResult["FOLDER"] . $arResult["URL_TEMPLATES"]["section"], "DETAIL_URL" => $arResult["FOLDER"] . $arResult["URL_TEMPLATES"]["element"], 'CONVERT_CURRENCY' => $arParams['CONVERT_CURRENCY'], 'CURRENCY_ID' => $arParams['CURRENCY_ID'], 'HIDE_NOT_AVAILABLE' => $arParams["HIDE_NOT_AVAILABLE"], 'LABEL_PROP' => $arParams['LABEL_PROP'], 'ADD_PICT_PROP' => $arParams['ADD_PICT_PROP'], 'PRODUCT_DISPLAY_MODE' => $arParams['PRODUCT_DISPLAY_MODE'], 'OFFER_ADD_PICT_PROP' => $arParams['OFFER_ADD_PICT_PROP'], 'OFFER_TREE_PROPS' => $arParams['OFFER_TREE_PROPS'], 'PRODUCT_SUBSCRIPTION' => $arParams['PRODUCT_SUBSCRIPTION'], 'SHOW_DISCOUNT_PERCENT' => $arParams['SHOW_DISCOUNT_PERCENT'], 'SHOW_OLD_PRICE' => $arParams['SHOW_OLD_PRICE'], 'MESS_BTN_BUY' => $arParams['MESS_BTN_BUY'], 'MESS_BTN_ADD_TO_BASKET' => $arParams['MESS_BTN_ADD_TO_BASKET'], 'MESS_BTN_SUBSCRIBE' => $arParams['MESS_BTN_SUBSCRIBE'], 'MESS_BTN_DETAIL' => $arParams['MESS_BTN_DETAIL'], 'MESS_NOT_AVAILABLE' => $arParams['MESS_NOT_AVAILABLE'], 'TEMPLATE_THEME' => isset($arParams['TEMPLATE_THEME']) ? $arParams['TEMPLATE_THEME'] : '', "ADD_SECTIONS_CHAIN" => isset($arParams["ADD_SECTIONS_CHAIN"]) ? $arParams["ADD_SECTIONS_CHAIN"] : '', "USE_MAIN_ELEMENT_SECTION" => 'Y'), $component);
?>
    </div>
  </div>



  <div id="compare_list_items_container" style="display: none">
  	  
  <?php 
$str = CUtil::PhpToJSObject(array_keys($_SESSION["CATALOG_COMPARE_LIST"][4]["ITEMS"]));
Trace($str);
$frame = new \Bitrix\Main\Page\FrameBuffered("compare_list_items_container", false);
$frame->begin('');
?>
  <input id="compare_list_items" type="hidden" value="<?php 
echo $str;
?>
">
  <?php 
$frame->end();
?>
  </div>



  <div id="sidebar">
Example #23
0
    echo $tiles;
    ?>
" class="link-table"><?php 
    echo GetMessage("WF_PRODUCT_VIEW_TABLE");
    ?>
</a>
  </div>
  <div class="product-catalog product-catalog02" id="wf-product-catalog">
    <ul style="position: relative;">
      <?php 
    if (isset($_GET["ajaxw"])) {
        Trace("before restart");
        $APPLICATION->RestartBuffer();
        Trace("after restart");
        include $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_before.php";
        Trace("after include");
    }
    ?>
      <!--RestartBuffer-->
      <?php 
    $PAGE_NUM = $_GET["PAGEN_1"];
    $num = 0;
    foreach ($arResult["ITEMS"] as $key => $arItem) {
        $key = $key + $PAGE_NUM * 12;
        $this->AddEditAction($arItem['ID'], $arItem['EDIT_LINK'], $strElementEdit);
        $this->AddDeleteAction($arItem['ID'], $arItem['DELETE_LINK'], $strElementDelete, $arElementDeleteParams);
        $strMainID = $this->GetEditAreaId($arItem['ID']);
        $isOffers = count($arItem["OFFERS"]) > 0;
        $arItemIDs = array('ID' => $strMainID, 'PICT' => $strMainID . '_pict', 'SECOND_PICT' => $strMainID . '_secondpict', 'QUANTITY' => $strMainID . '_quantity', 'QUANTITY_DOWN' => $strMainID . '_quant_down', 'QUANTITY_UP' => $strMainID . '_quant_up', 'QUANTITY_MEASURE' => $strMainID . '_quant_measure', 'BUY_LINK' => $strMainID . '_buy_link', 'SUBSCRIBE_LINK' => $strMainID . '_subscribe', 'PRICE' => $strMainID . '_price', 'DSC_PERC' => $strMainID . '_dsc_perc', 'SECOND_DSC_PERC' => $strMainID . '_second_dsc_perc', 'PROP_DIV' => $strMainID . '_sku_tree', 'PROP' => $strMainID . '_prop_', 'DISPLAY_PROP_DIV' => $strMainID . '_sku_prop', 'BASKET_PROP_DIV' => $strMainID . '_basket_prop');
        $strObName = 'ob' . preg_replace("/[^a-zA-Z0-9_]/", "x", $strMainID);
        $strTitle = isset($arItem["IPROPERTY_VALUES"]["ELEMENT_PREVIEW_PICTURE_FILE_TITLE"]) && '' != isset($arItem["IPROPERTY_VALUES"]["ELEMENT_PREVIEW_PICTURE_FILE_TITLE"]) ? $arItem["IPROPERTY_VALUES"]["ELEMENT_PREVIEW_PICTURE_FILE_TITLE"] : $arItem['NAME'];
Example #24
0
 public function PageWhere($DiscussionID, $Page, $Limit)
 {
     if (!Gdn::Cache()->ActiveEnabled() || !empty($this->_Where) || $this->_OrderBy[0][0] != 'c.DateInserted' || $this->_OrderBy[0][1] == 'desc') {
         return FALSE;
     }
     if ($Limit != C('Vanilla.Comments.PerPage', 30)) {
         return FALSE;
     }
     $CacheKey = "Comment.Page.{$Limit}.{$DiscussionID}.{$Page}";
     $Value = Gdn::Cache()->Get($CacheKey);
     Trace('CommentModel->PageWhere()');
     Trace($Value, $CacheKey);
     //      Gdn::Controller()->SetData('_PageCache', array($CacheKey, $Value));
     if ($Value === FALSE) {
         return FALSE;
     } elseif (is_array($Value)) {
         $Result = array('DateInserted >=' => $Value[0]);
         if (isset($Value[1])) {
             $Result['DateInserted <='] = $Value[1];
         }
         return $Result;
     }
     return FALSE;
 }
Example #25
0
 public function RunStructure($AddonCode = NULL, $Explicit = FALSE, $Drop = FALSE)
 {
     // Get the structure files for all of the enabled applications.
     $ApplicationManager = new Gdn_ApplicationManager();
     $Apps = $ApplicationManager->EnabledApplications();
     $AppNames = ConsolidateArrayValuesByKey($Apps, 'Folder');
     $Paths = array();
     foreach ($Apps as $Key => $AppInfo) {
         $Path = PATH_APPLICATIONS . "/{$AppInfo['Folder']}/settings/structure.php";
         if (file_exists($Path)) {
             $Paths[] = $Path;
         }
         Gdn::ApplicationManager()->RegisterPermissions($Key, $this->Validation);
     }
     // Execute the structures.
     $Database = Gdn::Database();
     $SQL = Gdn::SQL();
     $Structure = Gdn::Structure();
     foreach ($Paths as $Path) {
         include $Path;
     }
     // Execute the structures for all of the plugins.
     $PluginManager = Gdn::PluginManager();
     $Registered = $PluginManager->RegisteredPlugins();
     foreach ($Registered as $ClassName => $Enabled) {
         if (!$Enabled) {
             continue;
         }
         try {
             $Plugin = $PluginManager->GetPluginInstance($ClassName, Gdn_PluginManager::ACCESS_CLASSNAME);
             if (method_exists($Plugin, 'Structure')) {
                 Trace("{$ClassName}->Structure()");
                 $Plugin->Structure();
             }
         } catch (Exception $Ex) {
             // Do nothing, plugin wouldn't load/structure.
             if (Debug()) {
                 throw $Ex;
             }
         }
     }
 }
Example #26
0
 /**
  * Fetches the location of a view into a string and returns it. Returns
  * false on failure.
  *
  * @param string $View The name of the view to fetch. If not specified, it will use the value
  * of $this->View. If $this->View is not specified, it will use the value
  * of $this->RequestMethod (which is defined by the dispatcher class).
  * @param string $ControllerName The name of the controller that owns the view if it is not $this.
  *  - If the controller name is FALSE then the name of the current controller will be used.
  *  - If the controller name is an empty string then the view will be looked for in the base views folder.
  * @param string $ApplicationFolder The name of the application folder that contains the requested controller if it is not $this->ApplicationFolder.
  */
 public function fetchViewLocation($View = '', $ControllerName = false, $ApplicationFolder = false, $ThrowError = true)
 {
     // Accept an explicitly defined view, or look to the method that was called on this controller
     if ($View == '') {
         $View = $this->View;
     }
     if ($View == '') {
         $View = $this->RequestMethod;
     }
     if ($ControllerName === false) {
         $ControllerName = $this->ControllerName;
     }
     if (StringEndsWith($ControllerName, 'controller', true)) {
         $ControllerName = substr($ControllerName, 0, -10);
     }
     if (strtolower(substr($ControllerName, 0, 4)) == 'gdn_') {
         $ControllerName = substr($ControllerName, 4);
     }
     if (!$ApplicationFolder) {
         $ApplicationFolder = $this->ApplicationFolder;
     }
     //$ApplicationFolder = strtolower($ApplicationFolder);
     $ControllerName = strtolower($ControllerName);
     if (strpos($View, DS) === false) {
         // keep explicit paths as they are.
         $View = strtolower($View);
     }
     // If this is a syndication request, append the method to the view
     if ($this->SyndicationMethod == SYNDICATION_ATOM) {
         $View .= '_atom';
     } elseif ($this->SyndicationMethod == SYNDICATION_RSS) {
         $View .= '_rss';
     }
     $ViewPath2 = viewLocation($View, $ControllerName, $ApplicationFolder);
     $LocationName = concatSep('/', strtolower($ApplicationFolder), $ControllerName, $View);
     $ViewPath = arrayValue($LocationName, $this->_ViewLocations, false);
     if ($ViewPath === false) {
         // Define the search paths differently depending on whether or not we are in a plugin or application.
         $ApplicationFolder = trim($ApplicationFolder, '/');
         if (stringBeginsWith($ApplicationFolder, 'plugins/')) {
             $KeyExplode = explode('/', $ApplicationFolder);
             $PluginName = array_pop($KeyExplode);
             $PluginInfo = Gdn::pluginManager()->getPluginInfo($PluginName);
             $BasePath = val('SearchPath', $PluginInfo);
             $ApplicationFolder = val('Folder', $PluginInfo);
         } else {
             $BasePath = PATH_APPLICATIONS;
             $ApplicationFolder = strtolower($ApplicationFolder);
         }
         $SubPaths = array();
         // Define the subpath for the view.
         // The $ControllerName used to default to '' instead of FALSE.
         // This extra search is added for backwards-compatibility.
         if (strlen($ControllerName) > 0) {
             $SubPaths[] = "views/{$ControllerName}/{$View}";
         } else {
             $SubPaths[] = "views/{$View}";
             $SubPaths[] = 'views/' . stringEndsWith($this->ControllerName, 'Controller', true, true) . "/{$View}";
         }
         // Views come from one of four places:
         $ViewPaths = array();
         // 1. An explicitly defined path to a view
         if (strpos($View, DS) !== false && stringBeginsWith($View, PATH_ROOT)) {
             $ViewPaths[] = $View;
         }
         if ($this->Theme) {
             // 2. Application-specific theme view. eg. /path/to/application/themes/theme_name/app_name/views/controller_name/
             foreach ($SubPaths as $SubPath) {
                 $ViewPaths[] = PATH_THEMES . "/{$this->Theme}/{$ApplicationFolder}/{$SubPath}.*";
                 // $ViewPaths[] = CombinePaths(array(PATH_THEMES, $this->Theme, $ApplicationFolder, 'views', $ControllerName, $View . '.*'));
             }
             // 3. Garden-wide theme view. eg. /path/to/application/themes/theme_name/views/controller_name/
             foreach ($SubPaths as $SubPath) {
                 $ViewPaths[] = PATH_THEMES . "/{$this->Theme}/{$SubPath}.*";
                 //$ViewPaths[] = CombinePaths(array(PATH_THEMES, $this->Theme, 'views', $ControllerName, $View . '.*'));
             }
         }
         // 4. Application/plugin default. eg. /path/to/application/app_name/views/controller_name/
         foreach ($SubPaths as $SubPath) {
             $ViewPaths[] = "{$BasePath}/{$ApplicationFolder}/{$SubPath}.*";
             //$ViewPaths[] = CombinePaths(array(PATH_APPLICATIONS, $ApplicationFolder, 'views', $ControllerName, $View . '.*'));
         }
         // Find the first file that matches the path.
         $ViewPath = false;
         foreach ($ViewPaths as $Glob) {
             $Paths = safeGlob($Glob);
             if (is_array($Paths) && count($Paths) > 0) {
                 $ViewPath = $Paths[0];
                 break;
             }
         }
         //$ViewPath = Gdn_FileSystem::Exists($ViewPaths);
         $this->_ViewLocations[$LocationName] = $ViewPath;
     }
     // echo '<div>['.$LocationName.'] RETURNS ['.$ViewPath.']</div>';
     if ($ViewPath === false && $ThrowError) {
         Gdn::dispatcher()->passData('ViewPaths', $ViewPaths);
         throw NotFoundException('View');
         //         trigger_error(ErrorMessage("Could not find a '$View' view for the '$ControllerName' controller in the '$ApplicationFolder' application.", $this->ClassName, 'FetchViewLocation'), E_USER_ERROR);
     }
     if ($ViewPath2 != $ViewPath) {
         Trace("View paths do not match: {$ViewPath} != {$ViewPath2}", TRACE_WARNING);
     }
     return $ViewPath;
 }
 /**
  *
  * @param DiscussionsController $Sender
  * @param type $Args
  */
 public function DiscussionsController_Unanswered_Render($Sender, $Args)
 {
     $Sender->SetData('CountDiscussions', FALSE);
     // Add 'Ask a Question' button if using BigButtons.
     if (C('Plugins.QnA.UseBigButtons')) {
         $QuestionModule = new NewQuestionModule($Sender, 'plugins/QnA');
         $Sender->AddModule($QuestionModule);
     }
     // Remove announcements that aren't questions...
     $Sender->Data('Announcements')->Result();
     $Announcements = array();
     foreach ($Sender->Data('Announcements') as $i => $Row) {
         if (GetValue('Type', $Row) == 'Question') {
             $Announcements[] = $Row;
         }
     }
     Trace($Announcements);
     $Sender->SetData('Announcements', $Announcements);
     $Sender->AnnounceData = $Announcements;
 }
Example #28
0
 /**
  * Used by $this->Stash() to create & manage sessions for users & guests.
  *
  * This is a stop-gap solution until full session management for users &
  * guests can be imlemented.
  */
 private function _getStashSession($ValueToStash)
 {
     $CookieName = c('Garden.Cookie.Name', 'Vanilla');
     $Name = $CookieName . '-sid';
     // Grab the entire session record
     $SessionID = val($Name, $_COOKIE, '');
     // If there is no session, and no value for saving, return;
     if ($SessionID == '' && $ValueToStash == '') {
         return false;
     }
     $Session = Gdn::SQL()->select()->from('Session')->where('SessionID', $SessionID)->get()->firstRow();
     if (!$Session) {
         $SessionID = betterRandomString(32);
         $TransientKey = substr(md5(mt_rand()), 0, 11) . '!';
         // Save the session information to the database.
         Gdn::SQL()->insert('Session', array('SessionID' => $SessionID, 'UserID' => Gdn::session()->UserID, 'TransientKey' => $TransientKey, 'DateInserted' => Gdn_Format::toDateTime(), 'DateUpdated' => Gdn_Format::toDateTime()));
         Trace("Inserting session stash {$SessionID}");
         $Session = Gdn::SQL()->select()->from('Session')->where('SessionID', $SessionID)->get()->firstRow();
         // Save a session cookie
         $Path = c('Garden.Cookie.Path', '/');
         $Domain = c('Garden.Cookie.Domain', '');
         $Expire = 0;
         // If the domain being set is completely incompatible with the current domain then make the domain work.
         $CurrentHost = Gdn::request()->host();
         if (!stringEndsWith($CurrentHost, trim($Domain, '.'))) {
             $Domain = '';
         }
         safeCookie($Name, $SessionID, $Expire, $Path, $Domain);
         $_COOKIE[$Name] = $SessionID;
     }
     $Session->Attributes = @unserialize($Session->Attributes);
     if (!$Session->Attributes) {
         $Session->Attributes = array();
     }
     return $Session;
 }
Example #29
0
 /**
  * Examines the page at $Url for title, description & images. Be sure to check the resultant array for any Exceptions that occurred while retrieving the page. 
  * @param string $Url The url to examine.
  * @param integer $Timeout How long to allow for this request. Default Garden.SocketTimeout or 1, 0 to never timeout. Default is 0.
  * @return array an array containing Url, Title, Description, Images (array) and Exception (if there were problems retrieving the page).
  */
 function FetchPageInfo($Url, $Timeout = 3)
 {
     $PageInfo = array('Url' => $Url, 'Title' => '', 'Description' => '', 'Images' => array(), 'Exception' => FALSE);
     try {
         if (!defined('HDOM_TYPE_ELEMENT')) {
             require_once PATH_LIBRARY . '/vendors/simplehtmldom/simple_html_dom.php';
         }
         $PageHtml = ProxyRequest($Url, $Timeout, TRUE);
         $Dom = str_get_html($PageHtml);
         if (!$Dom) {
             throw new Exception('Failed to load page for parsing.');
         }
         /* Sample Facebook Open Graph code:
         
         <meta property="og:title" content="60 degrees in&nbsp;February" />
         <meta property="og:url" content="http://karinemily.wordpress.com/2012/02/02/60-degrees-in-february/" />
         <meta property="og:description" content="and Philadelphia explodes with babies, puppies, and hipsters." />
         <meta property="og:site_name" content="K a r i &#039; s" />
         <meta property="og:image" content="http://karinemily.files.wordpress.com/2012/02/dsc_0132.jpg?w=300&amp;h=300" />
         <meta property="og:image" content="http://karinemily.files.wordpress.com/2012/02/dsc_0214.jpg?w=300&amp;h=300" />
         <meta property="og:image" content="http://karinemily.files.wordpress.com/2012/02/dsc_0213.jpg?w=300&amp;h=300" />
         <meta property="og:image" content="http://karinemily.files.wordpress.com/2012/02/dsc_0221-version-2.jpg?w=300&amp;h=300" />
         
                   */
         // FIRST PASS: Look for open graph title, desc, images
         $PageInfo['Title'] = DomGetContent($Dom, 'meta[property=og:title]');
         Trace('Getting og:description');
         $PageInfo['Description'] = DomGetContent($Dom, 'meta[property=og:description]');
         foreach ($Dom->find('meta[property=og:image]') as $Image) {
             if (isset($Image->content)) {
                 $PageInfo['Images'][] = $Image->content;
             }
         }
         // SECOND PASS: Look in the page for title, desc, images
         if ($PageInfo['Title'] == '') {
             $PageInfo['Title'] = $Dom->find('title', 0)->plaintext;
         }
         if ($PageInfo['Description'] == '') {
             Trace('Getting meta description');
             $PageInfo['Description'] = DomGetContent($Dom, 'meta[name=description]');
         }
         // THIRD PASS: Look in the page contents
         if ($PageInfo['Description'] == '') {
             foreach ($Dom->find('p') as $element) {
                 Trace('Looking at p for description.');
                 if (strlen($element->plaintext) > 150) {
                     $PageInfo['Description'] = $element->plaintext;
                     break;
                 }
             }
             if (strlen($PageInfo['Description']) > 400) {
                 $PageInfo['Description'] = SliceParagraph($PageInfo['Description'], 400);
             }
         }
         // Final: Still nothing? remove limitations
         if ($PageInfo['Description'] == '') {
             foreach ($Dom->find('p') as $element) {
                 Trace('Looking at p for description (no restrictions)');
                 if (trim($element->plaintext) != '') {
                     $PageInfo['Description'] = $element->plaintext;
                     break;
                 }
             }
         }
         // Page Images
         if (count($PageInfo['Images']) == 0) {
             $Images = DomGetImages($Dom, $Url);
             $PageInfo['Images'] = array_values($Images);
         }
         $PageInfo['Title'] = HtmlEntityDecode($PageInfo['Title']);
         $PageInfo['Description'] = HtmlEntityDecode($PageInfo['Description']);
     } catch (Exception $ex) {
         $PageInfo['Exception'] = $ex->getMessage();
     }
     return $PageInfo;
 }
 protected function PollFeed($FeedURL, $LastImportDate)
 {
     $Pr = new ProxyRequest();
     $FeedRSS = $Pr->Request(array('URL' => $FeedURL));
     if (!$FeedRSS) {
         return FALSE;
     }
     $RSSData = simplexml_load_string($FeedRSS);
     if (!$RSSData) {
         return FALSE;
     }
     $Channel = GetValue('channel', $RSSData, FALSE);
     if (!$Channel) {
         return FALSE;
     }
     if (!array_key_exists('item', $Channel)) {
         return FALSE;
     }
     $Feed = $this->GetFeed($FeedURL, FALSE);
     $DiscussionModel = new DiscussionModel();
     $DiscussionModel->SpamCheck = FALSE;
     $LastPublishDate = GetValue('LastPublishDate', $Feed, date('c'));
     $LastPublishTime = strtotime($LastPublishDate);
     $FeedLastPublishTime = 0;
     foreach (GetValue('item', $Channel) as $Item) {
         $FeedItemGUID = trim((string) GetValue('guid', $Item));
         if (empty($FeedItemGUID)) {
             Trace('guid is not set in each item of the RSS.  Will attempt to use link as unique identifier.');
             $FeedItemGUID = GetValue('link', $Item);
         }
         $FeedItemID = substr(md5($FeedItemGUID), 0, 30);
         $ItemPubDate = (string) GetValue('pubDate', $Item, NULL);
         if (is_null($ItemPubDate)) {
             $ItemPubTime = time();
         } else {
             $ItemPubTime = strtotime($ItemPubDate);
         }
         if ($ItemPubTime > $FeedLastPublishTime) {
             $FeedLastPublishTime = $ItemPubTime;
         }
         if ($ItemPubTime < $LastPublishTime && !$Feed['Historical']) {
             continue;
         }
         $ExistingDiscussion = $DiscussionModel->GetWhere(array('ForeignID' => $FeedItemID));
         if ($ExistingDiscussion && $ExistingDiscussion->NumRows()) {
             continue;
         }
         $this->EventArguments['Publish'] = TRUE;
         $this->EventArguments['FeedURL'] = $FeedURL;
         $this->EventArguments['Feed'] =& $Feed;
         $this->EventArguments['Item'] =& $Item;
         $this->FireEvent('FeedItem');
         if (!$this->EventArguments['Publish']) {
             continue;
         }
         $StoryTitle = array_shift($Trash = explode("\n", (string) GetValue('title', $Item)));
         $StoryBody = (string) GetValue('description', $Item);
         $StoryPublished = date("Y-m-d H:i:s", $ItemPubTime);
         $ParsedStoryBody = $StoryBody;
         $ParsedStoryBody = '<div class="AutoFeedDiscussion">' . $ParsedStoryBody . '</div> <br /><div class="AutoFeedSource">Source: ' . $FeedItemGUID . '</div>';
         $DiscussionData = array('Name' => $StoryTitle, 'Format' => 'Html', 'CategoryID' => $Feed['Category'], 'ForeignID' => substr($FeedItemID, 0, 30), 'Body' => $ParsedStoryBody);
         // Post as Minion (if one exists) or the system user
         if (Gdn::PluginManager()->CheckPlugin('Minion')) {
             $Minion = Gdn::PluginManager()->GetPluginInstance('MinionPlugin');
             $InsertUserID = $Minion->GetMinionUserID();
         } else {
             $InsertUserID = Gdn::UserModel()->GetSystemUserID();
         }
         $DiscussionData[$DiscussionModel->DateInserted] = $StoryPublished;
         $DiscussionData[$DiscussionModel->InsertUserID] = $InsertUserID;
         $DiscussionData[$DiscussionModel->DateUpdated] = $StoryPublished;
         $DiscussionData[$DiscussionModel->UpdateUserID] = $InsertUserID;
         $this->EventArguments['FeedDiscussion'] =& $DiscussionData;
         $this->FireEvent('Publish');
         if (!$this->EventArguments['Publish']) {
             continue;
         }
         $InsertID = $DiscussionModel->Save($DiscussionData);
         $this->EventArguments['DiscussionID'] = $InsertID;
         $this->EventArguments['Vaidation'] = $DiscussionModel->Validation;
         $this->FireEvent('Published');
         // Reset discussion validation
         $DiscussionModel->Validation->Results(TRUE);
     }
     $FeedKey = self::EncodeFeedKey($FeedURL);
     $this->UpdateFeed($FeedKey, array('LastImport' => date('Y-m-d H:i:s'), 'LastPublishDate' => date('c', $FeedLastPublishTime)));
 }