/** * Log start of request, for adding to log entry later. */ private function log_start() { if ($this->logging) { $this->log_timestamp = microtime(TRUE); timer_start('openruth_net'); } }
function themeInit($archive) { timer_start(); $archive->parameter->pageSize = 5; if ($archive->is('single')) { $archive->content = prettify_replace($archive->content); $archive->content = url_target_replace($archive->content); } }
/** * Load the content selected by the URI and save the output in load_area. * Leave the parameters null if you want to load automatically the controllers * * @param string $controller selected controller * @param string $action selected action * @param string $params array of the selected actions * @param string $load_area selected load area where the controller is rendered */ function load_controller($controller = null, $action = null, $params = array(), $load_area = "center") { // transform the controller string to capitalized. e.g. user => user, news_list => news_list $controller = strtolower($controller); $controller_file = self::$controllers_dir . "{$controller}/{$controller}." . self::$controller_extension; // include the file if (file_exists($controller_file = self::$controllers_dir . "{$controller}/{$controller}." . self::$controller_extension)) { require_once $controller_file; } else { return trigger_error("CONTROLLER: FILE <b>{$controller_file}</b> NOT FOUND ", E_USER_WARNING); } // define the class name of the controller $class = $controller . self::$controller_class_name; // check if the controller class exists if (class_exists($class)) { $controller_obj = new $class($this); } else { return trigger_error("CONTROLLER: CLASS <b>{$controller}</b> NOT FOUND ", E_USER_WARNING); } if ($action) { // start benchmark timer_start("controller"); memory_usage_start("controller"); // start the output buffer ob_start(); // call the method filter_before call_user_func_array(array($controller_obj, "filter_before"), $params); // call the selected action $action_status = call_user_func_array(array($controller_obj, $action), $params); //call the method filter_after call_user_func_array(array($controller_obj, "filter_after"), $params); $html = ob_get_contents(); // close the output buffer ob_end_clean(); // verify that the action was executed if (false === $action_status) { $html = "Action <b>{$action}</b> not found in controller <b>{$class}</b>! Method not declared or declared with different private access"; } $this->loaded_controller[] = array("controller" => $controller, "execution_time" => timer("controller"), "memory_used" => memory_usage("controller")); // if it is in ajax mode print and stop the execution of the script if ($this->ajax_mode) { echo $html; $this->_draw_ajax(); } else { // save the output into the load_area array if (!isset($this->load_area_array[$load_area])) { $this->load_area_array[$load_area] = array(); } $this->load_area_array[$load_area][] = $html; } } }
/** * Rebuild the image * * @access public * @return void * @author Nicolas Juen */ public static function a_thumbnail_rebuild() { global $wpdb; // Get the nonce $nonce = isset($_POST['nonce']) ? $_POST['nonce'] : ''; // Time a the begining timer_start(); // Get the thumbnails $thumbnails = isset($_POST['thumbnails']) ? $_POST['thumbnails'] : NULL; // Check the nonce if (!wp_verify_nonce($nonce, 'regen')) { SIS_Admin_Main::displayJson(array('error' => _e('Trying to cheat ?', 'simple-image-sizes'))); } // Get the id $id = isset($_POST["id"]) ? $_POST["id"] : 0; SIS_Admin_Main::displayJson(SIS_Admin_Main::thumbnail_rebuild($id, $thumbnails)); }
function bootstrap_configuration() { if (version_compare(PHP_VERSION, PHP_REQUIRED, '<')) { header($_SERVER['SERVER_PROTOCOL'] . ' 500 PHP_VERSION'); exit; } if (get_magic_quotes_gpc() || get_magic_quotes_runtime()) { header($_SERVER['SERVER_PROTOCOL'] . ' 500 magic_quotes'); exit; } date_default_timezone_set('PRC'); ini_set('session.use_cookies', '1'); ini_set('session.use_only_cookies', '1'); ini_set('session.use_trans_sid', '0'); ini_set('session.cache_limiter', ''); timer_start(); set_error_handler('pyramid_error_handler'); set_exception_handler('pyramid_exception_handler'); }
/** * Rebuild the given attribute with the given thumbnails * * @param $att_id * @param $thumbnails * * @return array * @author Nicolas Juen */ public static function thumbnail_rebuild($att_id, $thumbnails = null) { // Time a the begining timer_start(); // Check Id if ((int) $att_id <= 0) { return array('time' => timer_stop(false, 4), 'error' => __('No id given in POST datas.', 'simple-image-sizes')); } // Get the path $fullsizepath = get_attached_file($att_id); // Regen the attachment if (false !== $fullsizepath && file_exists($fullsizepath)) { if (false == wp_update_attachment_metadata($att_id, self::wp_generate_attachment_metadata_custom($att_id, $fullsizepath, $thumbnails))) { return array('src' => wp_get_attachment_thumb_url($att_id), 'time' => timer_stop(false, 4), 'message' => sprintf(__('This file already exists in this size and have not been regenerated :<br/><a target="_blank" href="%1$s" >%2$s</a>', 'simple-image-sizes'), get_edit_post_link($att_id), get_the_title($att_id))); } } else { return array('src' => wp_get_attachment_thumb_url($att_id), 'time' => timer_stop(false, 4), 'error' => sprintf(__('This file does not exists and have not been regenerated :<br/><a target="_blank" href="%1$s" >%2$s</a>', 'simple-image-sizes'), get_edit_post_link($att_id), get_the_title($att_id))); } // Display the attachment url for feedback return array('time' => timer_stop(false, 4), 'src' => wp_get_attachment_thumb_url($att_id), 'title' => get_the_title($att_id)); }
private function sitebilder_inicializador($phase) { switch ($phase) { case SITEBILDER_CONFIGURATION: timer_start('config'); $this->LoadConfig(); $this->LoadConfigDb(); $this->LoadConfigSmarty(); $this->ConfigLocation(); break; case SITEBILDER_LANGUAGE: $this->ListLanguages(); $this->GetLanguage(); $this->LoadLanguage(); break; case SITEBILDER_ACCESS: if ($this->is_denied('host', ip_address())) { header('HTTP/1.1 403 Forbidden'); print 'Sorry, ' . check_plain(ip_address()) . ' has been banned.'; exit; } break; case SITEBILDER_PERFIL: $this->LoadPerfil(); break; case SITEBILDER_SESSION: session_start(); $this->LoadMap(); break; case SITEBILDER_PAGE: $this->LoadPages(); $this->LoadModulo(); break; case SITEBILDER_SAJAX: break; case SITEBILDER_FULL: break; } }
private static function &_query($query, $args = NULL) { $false = FALSE; if (empty($query)) { return $false; } if (!isset($GLOBALS['sql_query_count'])) { $GLOBALS['sql_query_count'] = 0; } else { $GLOBALS['sql_query_count']++; } if (utopia::DebugMode()) { $tID = 'QRY' . $GLOBALS['sql_query_count'] . ': ' . $query; timer_start($tID, $args); } $pdo = self::connect(); $pdo->reset(); if (is_array($args)) { foreach ($args as $a) { $pdo->addByVal($a, self::getType($a)); } } try { self::$queryCount++; $stm = $pdo->call($query); $stm->setFetchMode(PDO::FETCH_ASSOC); } catch (Exception $e) { if (utopia::DebugMode()) { $timetaken = timer_end($tID); } throw $e; } if (utopia::DebugMode()) { $timetaken = timer_end($tID); } return $stm; }
/** * Index all posts for a site or network wide * * @synopsis [--setup] [--network-wide] [--posts-per-page] [--no-bulk] [--offset] [--show-bulk-errors] * @param array $args * * @since 0.1.2 * * @param array $assoc_args */ public function index($args, $assoc_args) { $this->_connect_check(); if (!empty($assoc_args['posts-per-page'])) { $assoc_args['posts-per-page'] = absint($assoc_args['posts-per-page']); } else { $assoc_args['posts-per-page'] = 350; } if (!empty($assoc_args['offset'])) { $assoc_args['offset'] = absint($assoc_args['offset']); } else { $assoc_args['offset'] = 0; } $total_indexed = 0; /** * Prior to the index command invoking * Useful for deregistering filters/actions that occur during a query request * * @since 1.4.1 */ do_action('ep_wp_cli_pre_index', $args, $assoc_args); // Deactivate our search integration $this->deactivate(); timer_start(); // Run setup if flag was passed if (isset($assoc_args['setup']) && true === $assoc_args['setup']) { // Right now setup is just the put_mapping command, as this also deletes the index(s) first $this->put_mapping($args, $assoc_args); } if (isset($assoc_args['network-wide']) && is_multisite()) { if (!is_numeric($assoc_args['network-wide'])) { $assoc_args['network-wide'] = 0; } WP_CLI::log(__('Indexing posts network-wide...', 'elasticpress')); $sites = ep_get_sites($assoc_args['network-wide']); foreach ($sites as $site) { switch_to_blog($site['blog_id']); $result = $this->_index_helper(isset($assoc_args['no-bulk']), $assoc_args['posts-per-page'], $assoc_args['offset'], isset($assoc_args['show-bulk-errors'])); $total_indexed += $result['synced']; WP_CLI::log(sprintf(__('Number of posts synced on site %d: %d', 'elasticpress'), $site['blog_id'], $result['synced'])); if (!empty($result['errors'])) { WP_CLI::error(sprintf(__('Number of post sync errors on site %d: %d', 'elasticpress'), $site['blog_id'], count($result['errors']))); } restore_current_blog(); } WP_CLI::log(__('Recreating network alias...', 'elasticpress')); $this->_create_network_alias(); WP_CLI::log(sprintf(__('Total number of posts indexed: %d', 'elasticpress'), $total_indexed)); } else { WP_CLI::log(__('Indexing posts...', 'elasticpress')); $result = $this->_index_helper(isset($assoc_args['no-bulk']), $assoc_args['posts-per-page'], $assoc_args['offset'], isset($assoc_args['show-bulk-errors'])); WP_CLI::log(sprintf(__('Number of posts synced on site %d: %d', 'elasticpress'), get_current_blog_id(), $result['synced'])); if (!empty($result['errors'])) { WP_CLI::error(sprintf(__('Number of post sync errors on site %d: %d', 'elasticpress'), get_current_blog_id(), count($result['errors']))); } } WP_CLI::log(WP_CLI::colorize('%Y' . __('Total time elapsed: ', 'elasticpress') . '%N' . timer_stop())); // Reactivate our search integration $this->activate(); WP_CLI::success(__('Done!', 'elasticpress')); }
public function ShowData($dataset = null) { echo '<h1>' . $this->GetTitle() . '</h1>'; echo '{list.' . get_class($this) . '}'; array_sort_subkey($this->fields, 'order'); $this->GetLimit($limit, $page); if (!$dataset) { $dataset = $this->GetDataset(); } $dataset->GetPage($page, $limit); $num_rows = $dataset->CountRecords(); uEvents::TriggerEvent('OnShowDataList', $this); // first draw header for list if (!isset($GLOBALS['inlineListCount'])) { $GLOBALS['inlineListCount'] = 0; } else { $GLOBALS['inlineListCount']++; } ob_start(); if (!$this->isAjax) { echo '<form class="uf" action="" onsubmit="this.action = window.location" method="post"><input type="hidden" name="__ajax" value="updateField">'; } echo "<div class=\"table-wrapper\"><table class=\"" . get_class($this) . " layoutListSection module-content\">"; $sectionFieldTitles = array(); // TODO: pagination for list record display if (!$this->flag_is_set(LIST_HIDE_HEADER)) { echo '<thead>'; ob_start(); // start of SECTION headers if (count($this->layoutSections) > 1) { echo '<tr>'; // need first 'empty' column for buttons? if ($this->flag_is_set(ALLOW_DELETE)) { echo "<td> </td>"; } $sectionCount = 0; $sectionID = NULL; $keys = array_keys($this->fields); $lastFieldName = end($keys); foreach ($this->fields as $fieldName => $fieldData) { if ($fieldData['visiblename'] === NULL) { continue; } if ($sectionID === NULL) { $sectionID = $fieldData['layoutsection']; } if ($fieldData['layoutsection'] !== $sectionID) { // write the section, and reset the count $sectionName = $this->layoutSections[$sectionID]['title']; $secClass = empty($sectionName) ? '' : ' sectionHeader'; echo "<td colspan=\"{$sectionCount}\" class=\"{$secClass}\">" . nl2br($sectionName) . "</td>"; $sectionCount = 0; $sectionID = $fieldData['layoutsection']; } $sectionFieldTitles[$sectionID] = array_key_exists($sectionID, $sectionFieldTitles) ? $sectionFieldTitles[$sectionID] : !empty($fieldData['visiblename']); $sectionCount++; } $sectionName = $this->layoutSections[$sectionID]['title']; $secClass = empty($sectionName) ? '' : ' sectionHeader'; echo "<td colspan=\"{$sectionCount}\" class=\"{$secClass}\">" . nl2br($sectionName) . "</td>"; echo "</tr>"; } // start of FIELD headers $colcount = 0; echo '<tr class="field-headers">'; if ($this->flag_is_set(ALLOW_DELETE)) { echo '<th"></th>'; $colcount++; } foreach ($this->fields as $fieldName => $fieldData) { if ($fieldData['visiblename'] === NULL) { continue; } $colcount++; // sort? $icon = ''; $o = $this->GetOrderBy(true); if (is_array($o)) { foreach ($o as $order) { if (strpos($order, '`' . $fieldName . '`') !== FALSE) { $icon = ' sort-up'; if (stripos($order, 'desc') !== FALSE) { $icon = ' sort-down'; } break; } } } echo '<th class="field-' . $fieldName . ' sortable' . $icon . '" data-field="' . $fieldName . '" data-mid="' . $this->GetModuleId() . '">'; // title echo nl2br($fieldData['visiblename']); echo "</th>"; } echo '</tr>'; // close column headers $header_output = ob_get_clean(); if ($this->flag_is_set(ALLOW_FILTER) && $this->hasEditableFilters === true && $this->hideFilters !== TRUE) { echo '<tr class="noprint"><td class="uFilters" colspan="' . $colcount . '">'; // other filters foreach ($this->filters as $fType) { foreach ($fType as $filterset) { //flag_is_set($fieldData['options'],ALLOW_FILTER)) { foreach ($filterset as $filterInfo) { if ($filterInfo['it'] === itNONE) { continue; } echo $this->GetFilterBox($filterInfo); } } } echo '</td></tr>'; } if ($num_rows > 0 || $this->flag_is_set(ALLOW_ADD) || $this->hasEditableFilters === true) { echo $header_output; } echo "</thead>\n"; } // now display data rows // process POST filters $total = array(); $totalShown = array(); timer_start('Draw Rows: ' . get_class($this)); $gUrl = ''; $body = "<tbody{$gUrl}>"; if ($num_rows == 0) { } else { $i = 0; $fields = $this->GetFields(); while ($row = $dataset->fetch()) { $i++; // move totals here foreach ($fields as $fieldName => $fieldData) { switch ($this->GetFieldType($fieldName)) { case ftNUMBER: case ftCURRENCY: case ftPERCENT: if (!array_key_exists($fieldName, $total)) { $total[$fieldName] = 0; } if (!array_key_exists($fieldName, $totalShown)) { $totalShown[$fieldName] = 0; } $preProcessValue = floatval(preg_replace('/[^0-9\\.-]/', '', $this->PreProcess($fieldName, $row[$fieldName], $row))); if ($i <= 150) { $totalShown[$fieldName] += $preProcessValue; } $total[$fieldName] += $preProcessValue; break; default: break; } } $body .= $this->DrawRow($row); } } $body .= "</tbody>"; timer_end('Draw Rows: ' . get_class($this)); $foot = ''; $canadd = false; foreach ($this->fields as $fieldName => $fieldData) { if ($this->flag_is_set(ALLOW_ADD, $fieldName)) { $canadd = true; break; } } if ($canadd) { $hideNew = $this->GetMaxRows() && $num_rows >= $this->GetMaxRows() ? ' style="display:none"' : ''; $foot .= '<tr class="newRow"' . $hideNew . '>'; if ($this->flag_is_set(ALLOW_DELETE)) { $foot .= "<td class=\"new-ident\"></td>"; } foreach ($this->fields as $fieldName => $fieldData) { if ($fieldData['visiblename'] === NULL) { continue; } $classes = array(); $class = count($classes) > 0 ? ' class="' . join(' ', $classes) . '"' : ''; if ($this->flag_is_set(ALLOW_ADD, $fieldName)) { $foot .= "<td{$class}>" . $this->GetCell($fieldName, NULL) . '</td>'; } // TODO: Default value not showing on new records (list) } $foot .= '</tr>'; } if (!empty($total) && $this->flag_is_set(SHOW_TOTALS)) { $foot .= '<tr>'; if ($this->flag_is_set(ALLOW_DELETE)) { $foot .= "<td class=\"totals-ident\"></td>"; } foreach ($this->fields as $fieldName => $fieldData) { if ($fieldData['visiblename'] === NULL) { continue; } $classes = array(); $class = count($classes) > 0 ? ' class="' . join(' ', $classes) . '"' : ''; if (array_key_exists($fieldName, $total)) { $foot .= "<td{$class}><b>"; if ($totalShown[$fieldName] != $total[$fieldName]) { $foot .= htmlentities($this->PreProcess($fieldName, $totalShown[$fieldName])) . '(shown)<br/>'; } $foot .= htmlentities($this->PreProcess($fieldName, $total[$fieldName])); $foot .= '</b></td>'; } else { $foot .= "<td{$class}></td>"; } } $foot .= '</tr>'; } if (!empty($foot)) { echo "<tfoot>{$foot}</tfoot>"; } echo $body; // now finish table echo "</table></div>"; //"</div>"; if (!$this->isAjax) { echo '</form>'; } if ($limit) { $pages = max(ceil($num_rows / $limit), 1); ob_start(); utopia::OutputPagination($pages, '_p_' . $this->GetModuleId()); $pagination = ob_get_clean(); if ($pagination) { echo '<div class="pagination right module-content">' . $pagination . '</div>'; } } echo '<div class="right module-content">Showing ' . ($page * $limit + 1) . ' - ' . min($page * $limit + $limit, $num_rows) . ' of ' . $num_rows . '</div>'; $cont = ob_get_clean(); echo $cont; }
/** * добавляет в глобальный шаблон блоки */ function get_blocks($blocks = array()) { foreach ($blocks as $block_name => $block) { # создаём объект $module_loader =& Registry::get('TModuleLoader'); $class_name = isset($block['class']) ? $block['class'] : DEFAULT_CLASS; //$GLOBALS['blocks'][$class_name] = $module_loader->getModuleObject($class_name); $GLOBALS['blocks'][$class_name] =& Registry::get($class_name); } foreach ($blocks as $block_name => $block) { timer_start('block=' . $block_name); # массив данных текущего блока $data = array(); $class_name = isset($block['class']) ? $block['class'] : DEFAULT_CLASS; $block['cache'] = isset($block['cache']) ? $block['cache'] : false; $tables = isset($block['tables']) ? $block['tables'] : array(); $block['cache_tables'] = isset($block['cache_tables']) ? $block['cache_tables'] : array(); if (CACHE_BLOCKS && $block['cache']) { // Очистка папки cache/blocks с вероятностью 0.001 if (rand(0, 999) == 13) { $this->cleanCache(); } $cache_id = md5($module_loader->callModuleMethod($class_name, "_cache", array_merge($block, array('block_name' => $block_name)))); if ($this->is_cached($this->content['type'], $block_name, $cache_id, $tables)) { $data = $this->get_from_cache($this->content['type'], $block_name, $cache_id); } else { $data = $this->generate_block_data($block_name, $block); $this->save_in_cache($this->content['type'], $block_name, $cache_id, $data); } } else { $data = $this->generate_block_data($block_name, $block); } $this->tpl->assign((array) $data); timer_end('block=' . $block_name); } }
$row['module_name']::Initialise(); timer_end('Init: ' . $row['module_name']); } timer_end('Static Initialise'); uConfig::DefineConfig(); uConfig::ValidateConfig(); uEvents::TriggerEvent('ConfigDefined'); timer_start('Before Init'); uEvents::TriggerEvent('BeforeInit'); timer_end('Before Init'); timer_start('Table Initialise'); uTableDef::TableExists(null); // cache table exists $allmodules = utopia::GetModulesOf('uTableDef'); foreach ($allmodules as $row) { // must run second due to requiring GLOB_MOD to be setup fully timer_start('Init: ' . $row['module_name']); $obj = utopia::GetInstance($row['module_name']); $obj->AssertTable(); // setup Parents timer_end('Init: ' . $row['module_name']); } timer_end('Table Initialise'); define('INIT_COMPLETE', TRUE); timer_start('After Init'); uEvents::TriggerEvent('InitComplete'); uEvents::TriggerEvent('AfterInit'); timer_end('After Init'); if ($_SERVER['HTTP_HOST'] !== 'cli') { utopia::UseTemplate(TEMPLATE_DEFAULT); }
# pop3-2-b2 mail to blog # v0.3 20020716 # with photo attachment email hack # # Line 223 (or so) is the line that # scales the image and puts it on the left. # Change the left; to right; or whatever you want # Change the width and height options also # Next is to click-through to original image # # Line 263 (or so) has the category stuff # there is a comment at the end of the section # require_once 'wp-config.php'; timer_start(); $use_cache = 1; $output_debugging_info = 0; # =1 if you want to output debugging info $time_difference = get_settings('time_difference'); //if ($use_phoneemail) { // // if you're using phone email, the email will already be in your timezone // $time_difference = 0; //} //Get Server Time Zone // If Server Time Zone is not collect, Please comment out following line; $server_timezone = date("O") / 100; // If Server Time Zone is not collect, Please uncomment following line and set collect timezone value; // $server_timezone = 9 $weblog_timezone = $server_timezone + $time_difference; error_reporting(2037);
function wp_mail_receive() { global $xoopsDB, $wpdb, $wp_id, $siteurl, $blog_charset, $wp_pop3; require_once ABSPATH . WPINC . '/class-pop3.php'; timer_start(); $use_cache = 1; $time_difference = get_settings('time_difference'); // Get Server Time Zone // If Server Time Zone is not collect, Please comment out following line; $server_timezone = date("O"); // echo "Server TimeZone is ".date('O')."<br />"; // If Server Time Zone is not collect, Please uncomment following line and set collect timezone value; // $server_timezone = "+0900"; //This is a sample value for JST+0900 $server_timezone = $server_timezone / 100; $weblog_timezone = $server_timezone + $time_difference; error_reporting(2037); $wp_pop3 = new POP3(); if (!$wp_pop3->connect(get_settings('mailserver_url'), get_settings('mailserver_port'))) { echo "Ooops {$wp_pop3->ERROR} <br />\n"; return; } $Count = $wp_pop3->login(get_settings('mailserver_login'), get_settings('mailserver_pass')); if ($Count == false) { if (!$wp_pop3->FP) { echo "Oooops Login Failed: {$wp_pop3->ERROR}<br />\n"; } else { echo "No Message<br />\n"; $wp_pop3->quit(); } return; } // ONLY USE THIS IF YOUR PHP VERSION SUPPORTS IT! register_shutdown_function('wp_mail_quit'); for ($iCount = 1; $iCount <= $Count; $iCount++) { $MsgOne = $wp_pop3->get($iCount); if (!$MsgOne || gettype($MsgOne) != 'array') { echo "oops, {$wp_pop3->ERROR}<br />\n"; $wp_pop3->quit(); return; } $content = ''; $content_type = ''; $boundary = ''; $att_boundary = ''; $hatt_boundary = ''; $bodysignal = 0; $dmonths = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); while (list($lineNum, $line) = each($MsgOne)) { if (strlen($line) < 3) { $bodysignal = 1; } if ($bodysignal) { $content .= $line; } else { if (preg_match('/^Content-Type:\\s+(.*?)\\;/i', $line, $match)) { $content_type = $match[1]; $content_type = strtolower($match[1]); } if ($content_type == 'multipart/mixed' && preg_match('/boundary=(?:")?([^;"\\s\\n]*?)(?:")?\\s*(?:$|;)/', $line, $match) && $att_boundary == '') { $att_boundary = trim($match[1]); } if ($content_type == 'multipart/alternative' && preg_match('/boundary=(?:")?([^;"\\s\\n]*?)(?:")?\\s*(?:$|;)/', $line, $match) && $boundary == '') { $boundary = trim($match[1]); } if ($content_type == 'multipart/related' && preg_match('/boundary=(?:")?([^;"\\s\\n]*?)(?:")?\\s*(?:$|;)/', $line, $match) && $hatt_boundary == '') { $hatt_boundary = trim($match[1]); } if (preg_match('/Subject: /', $line)) { $subject = trim($line); $subject = substr($subject, 9, strlen($subject) - 9); if (function_exists('mb_decode_mimeheader')) { $subject1 = mb_decode_mimeheader($subject); if ($subject != $subject) { $sub_charset = mb_internal_encoding(); } else { $sub_charset = "auto"; } $subject = $subject1; } if (get_settings('use_phoneemail')) { $subject = explode(get_settings('phoneemail_separator'), $subject); $subject = trim($subject[0]); } } if (preg_match('/Date: /', $line)) { // of the form '20 Mar 2002 20:32:37' $ddate = trim($line); $ddate = str_replace('Date: ', '', $ddate); if (strpos($ddate, ',')) { $ddate = trim(substr($ddate, strpos($ddate, ',') + 1, strlen($ddate))); } $date_arr = explode(' ', $ddate); $date_time = explode(':', $date_arr[3]); $ddate_H = $date_time[0]; $ddate_i = $date_time[1]; $ddate_s = $date_time[2]; $ddate_m = $date_arr[1]; $ddate_d = $date_arr[0]; $ddate_Y = $date_arr[2]; $mail_timezone = trim(ereg_replace("\\([^)]*\\)", "", $date_arr[4])) / 100; // echo "Email TimeZone is {$date_arr[4]}<br />"; $mail_time_difference = $weblog_timezone - $mail_timezone; for ($i = 0; $i < 12; $i++) { if ($ddate_m == $dmonths[$i]) { $ddate_m = $i + 1; } } $ddate_U = mktime($ddate_H, $ddate_i, $ddate_s, $ddate_m, $ddate_d, $ddate_Y); $ddate_U = $ddate_U + $mai_time_difference * 3600; $post_date = date('Y-m-d H:i:s', $ddate_U); } } } if (!ereg(get_settings('subjectprefix'), $subject)) { continue; } $charset = ""; $ncharset = preg_match("/\\s?charset=\"?([A-Za-z0-9\\-]*)\"?/i", $content, $matches); if ($ncharset) { $charset = $matches[1]; } $ddate_today = time() + $time_difference * 3600; $ddate_difference_days = ($ddate_today - $ddate_U) / 86400; if ($ddate_difference_days > 14) { echo "Too old<br />\n"; continue; } if (preg_match('/' . get_settings('subjectprefix') . '/', $subject)) { $userpassstring = ''; echo "<div style=\"border: 1px dashed #999; padding: 10px; margin: 10px;\">\n"; echo "<p><b>{$iCount}</b></p><p><b>Subject: </b>{$subject}</p>\n"; $subject = trim(str_replace(get_settings('subjectprefix'), '', $subject)); $attachment = false; if ($att_boundary) { $contents = explode('--' . $att_boundary, $content); $content = $contents[1]; $ncharset = preg_match("/\\s?charset=\"?([A-Za-z0-9\\-]*)\"?/i", $content, $matches); if ($ncharset) { $charset = $matches[1]; } $content = explode("\r\n\r\n", $content, 2); $content = $content[1]; } if ($hatt_boundary) { $contents = explode('--' . $hatt_boundary, $content); $content = $contents[1]; if (preg_match('/Content-Type: multipart\\/alternative\\;\\s*boundary\\=(?:")?([^";\\s\\n]*?)(?:")?\\s*(?:;|\\n|$)"/i', $content, $matches)) { $boundary = trim($matches[1]); $content = explode('--' . $boundary, $content); $content = $content[2]; } $ncharset = preg_match("/charset=\"?([^\"]*)\"?/i", $content, $matches); if ($ncharset) { $charset = $matches[1]; } $content = explode('Content-Transfer-Encoding: quoted-printable', $content); $content = strip_tags($content[1], '<img><p><br><i><b><u><em><strong><strike><font><span><div><dl><dt><dd><ol><ul><li>,<table><tr><td>'); } else { if ($boundary) { $content = explode('--' . $boundary, $content); $content = $content[2]; if (preg_match('/Content-Type: multipart\\/related\\;\\s*boundary=(?:")?([^";\\s\\n]*?)(?:")?\\s*(?:;|\\n|$)/i', $content, $matches)) { $hatt_boundary = trim($matches[1]); $contents = explode('--' . $hatt_boundary, $content); $content = $contents[1]; } $ncharset = preg_match("/charset=\"?([^\"]*)\"?/i", $content, $matches); if ($ncharset) { $charset = $matches[1]; } $content = explode('Content-Transfer-Encoding: quoted-printable', $content); $content = strip_tags($content[1], '<img><p><br><i><b><u><em><strong><strike><font><span><div><dl><dt><dd><ol><ul><li>,<table><tr><td>'); } } $content = trim($content); echo "<p><b>Content-type:</b> {$content_type}, <b>boundary:</b> {$boundary}</p>\n"; echo "<p><b>att_boundary:</b> {$att_boundary}, <b>hatt_boundary:</b> {$hatt_boundary}</p>\n"; echo "<p><b>charset:</b>{$charset}, <b>BLOG charset:</b>{$blog_charset}</p>\n"; // echo "<p><b>Raw content:</b><br /><pre>".$content.'</pre></p>'; if ($charset == "" || trim(strtoupper($charset)) == "ISO-2022-JP") { $charset = "JIS"; } if (trim(strtoupper($charset)) == "SHIFT_JIS") { $charset = "SJIS"; } $btpos = strpos($content, get_settings('bodyterminator')); if ($btpos) { $content = substr($content, 0, $btpos); } $content = trim($content); $blah = explode("\n", preg_replace("/^[\n\r\\s]*/", "", strip_tags($content))); $firstline = preg_replace("/[\n\r]/", "", $blah[0]); $secondline = $blah[1]; if (get_settings('use_phoneemail')) { echo "<p><b>Use Phone Mail:</b> Yes</p>\n"; $btpos = strpos($firstline, get_settings('phoneemail_separator')); if ($btpos) { $userpassstring = trim(substr($firstline, 0, $btpos)); $content = trim(substr($content, $btpos + strlen(get_settings('phoneemail_separator')), strlen($content))); $btpos = strpos($content, get_settings('phoneemail_separator')); if ($btpos) { $userpassstring = trim(substr($content, 0, $btpos)); $content = trim(substr($content, $btpos + strlen(get_settings('phoneemail_separator')), strlen($content))); } } $contentfirstline = $blah[1]; } else { echo "<p><b>Use Phone Mail:</b> No</p>\n"; $userpassstring = strip_tags($firstline); $contentfirstline = ''; } $flat = 999.0; $flon = 999.0; $secondlineParts = explode(':', strip_tags($secondline)); if (strncmp($secondlineParts[0], "POS", 3) == 0) { echo "Found POS:<br>\n"; // echo "Second parts is:".$secondlineParts[1]; // the second line is the postion listing line $secLineParts = explode(',', $secondlineParts[1]); $flatStr = $secLineParts[0]; $flonStr = $secLineParts[1]; // echo "String are ".$flatStr.$flonStr; $flat = floatval($secLineParts[0]); $flon = floatval($secLineParts[1]); // echo "values are ".$flat." and ".$flon; // ok remove that position... we should not have it in the final output $content = str_replace($secondline, '', $content); } $blah = explode(':', $userpassstring); $user_login = $blah[0]; $user_pass = $blah[1]; if (function_exists('mb_convert_encoding')) { $user_login = mb_convert_encoding(trim($user_login), $blog_charset, $charset); } else { $user_login = trim($user_login); } $content = $contentfirstline . str_replace($firstline, '', $content); $content = trim($content); // Please uncomment following line, only if you want to check user and password. // echo "<p><b>Login:</b> $user_login, <b>Pass:</b> $user_pass</p>"; echo "<p><b>Login:</b> {$user_login}, <b>Pass:</b> *********</p>"; if ($xoopsDB) { $sql = "SELECT ID, user_level FROM {$wpdb->users[$wp_id]} WHERE user_login='******' ORDER BY ID DESC LIMIT 1"; $result = $wpdb->get_row($sql); if (!$result) { echo "<p><b>Wrong Login.</b></p></div>\n"; continue; } else { $sql = "SELECT * FROM " . $xoopsDB->prefix('users') . " WHERE uname='{$user_login}' AND pass='******' ORDER BY uid DESC LIMIT 1"; $result1 = $wpdb->get_row($sql); if (!$result1) { echo "<p><b>Wrong login or password.</b></p></div>\n"; continue; } } } else { $sql = "SELECT ID, user_level FROM {$wpdb->users[$wp_id]} WHERE user_login='******' AND user_pass='******' ORDER BY ID DESC LIMIT 1"; $result = $wpdb->get_row($sql); if (!$result) { echo "<p><b>Wrong login or password.</b></p></div>\n"; continue; } } $user_level = $result->user_level; $post_author = $result->ID; if ($user_level > 0) { $post_title = xmlrpc_getposttitle($content); if ($post_title == '') { $post_title = $subject; } $post_category = get_settings('default_category'); if (preg_match('/<category>(.+?)<\\/category>/is', $content, $matchcat)) { $post_category = xmlrpc_getpostcategory($content); } if ($post_category == '') { $post_category = get_settings('default_post_category'); } if (function_exists('mb_convert_encoding')) { echo "Subject : " . mb_convert_encoding($subject, $blog_charset, $sub_charset) . " <br />\n"; } else { echo "Subject : " . $subject . " <br />\n"; } echo "Category : {$post_category} <br />\n"; if (!get_settings('emailtestonly')) { // Attaching Image Files Save if ($att_boundary != "") { $attachment = wp_getattach($contents[2], trim($user_login), 1); } if ($boundary != "" && $hatt_boundary != "") { for ($i = 2; $i < count($contents); $i++) { $hattachment = wp_getattach($contents[$i], trim($user_login), 0); if ($hattachment) { if (preg_match("/Content-Id: \\<([^\\>]*)>/i", $contents[$i], $matches)) { $content = preg_replace("/(cid:" . preg_quote($matches[1]) . ")/", "{$siteurl}/attach/" . $hattachment, $content); } } } } if ($boundary != "") { $content = preg_replace("/\\=[\r\n]/", "", $content); $content = preg_replace("/[\r\n]/", " ", $content); } $content = preg_replace("|\n([^\n])|", " \$1", $content); $content = preg_replace("/\\=([0-9a-fA-F]{2,2})/e", "pack('c',base_convert('\\1',16,10))", $content); if (function_exists('mb_convert_encoding')) { $content = addslashes(mb_convert_encoding(trim($content), $blog_charset, $charset)); $post_title = addslashes(trim(mb_convert_encoding($post_title, $blog_charset, $sub_charset))); } else { $content = addslashes(trim($content)); $post_title = addslashes(trim($post_title)); } // If we find an attachment, add it to the post if ($attachment) { if (file_exists("attach/thumb-" . $attachment)) { $content = "<a href=\"" . $siteurl . "/attach/" . $attachment . "\"><img style=\"float: left;\" hspace=\"6\" src = \"" . $siteurl . "/attach/thumb-" . $attachment . "\" alt=\"moblog\" ></a>" . $content . "<br clear=left>"; } else { $content = "<a href=\"" . $siteurl . "/attach/" . $attachment . "\"><img style=\"float: left;\" hspace=\"6\" src = \"" . $siteurl . "/attach/" . $attachment . "\" alt=\"moblog\" ></a>" . $content . "<br clear=left>"; } } if ($flat > 500) { $sql = "INSERT INTO {$wpdb->posts[$wp_id]} (post_author, post_date, post_content, post_title, post_category) VALUES ({$post_author}, '{$post_date}', '{$content}', '{$post_title}', {$post_category})"; } else { $sql = "INSERT INTO {$wpdb->posts[$wp_id]} (post_author, post_date, post_content, post_title, post_category, post_lat, post_lon) VALUES ({$post_author}, '{$post_date}', '{$content}', '{$post_title}', {$post_category}, {$flat}, {$flon})"; } $result = $wpdb->query($sql); $post_ID = $wpdb->insert_id; echo "Post ID = {$post_ID}<br />\n"; if (isset($sleep_after_edit) && $sleep_after_edit > 0) { sleep($sleep_after_edit); } $blog_ID = 1; if ($flat < 500) { pingGeoUrl($post_ID); } // Double check it's not there already $exists = $wpdb->get_row("SELECT * FROM {$wpdb->post2cat[$wp_id]} WHERE post_id = {$post_ID} AND category_id = {$post_category}"); if (!$exists && $result) { $wpdb->query("\n\t\t\t\t\t\tINSERT INTO {$wpdb->post2cat[$wp_id]}\n\t\t\t\t\t\t(post_id, category_id)\n\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t({$post_ID}, {$post_category})\n\t\t\t\t\t\t"); } pingWeblogs($blog_ID); pingBlogs($blog_ID); // pingback($content, $post_ID); do_action('publish_post', $post_ID); do_action('publish_phone', $post_ID); } echo "\n<p><b>Posted title:</b> {$post_title}<br />\n"; echo "<b>Posted content:</b><br /><pre>" . $content . "</pre></p>\n"; if (!$wp_pop3->delete($iCount)) { echo "<p>Oops " . $wp_pop3->ERROR . "</p></div>\n"; $wp_pop3->reset(); return; } else { echo "<p>Mission complete, message <strong>{$iCount}</strong> deleted.</p>\n"; } } else { echo "<p><strong>Level 0 users can\\'t post.</strong></p>\n"; } echo "</div>\n"; } } $wp_pop3->quit(); timer_stop($output_debugging_info); return; }
/** * Overrides Drupal core HTTP request function with Guzzle. * * @see drupal_http_request() */ function bangpound_drupal_http_request($url, array $options = array()) { $result = new stdClass(); // Parse the URL and make sure we can handle the schema. $uri = @parse_url($url); if ($uri == FALSE) { $result->error = 'unable to parse URL'; $result->code = -1001; return $result; } if (!isset($uri['scheme'])) { $result->error = 'missing schema'; $result->code = -1002; return $result; } timer_start(__FUNCTION__); // Merge the default options. $options += array('headers' => array(), 'method' => 'GET', 'data' => NULL, 'max_redirects' => 3, 'timeout' => 30.0, 'context' => NULL); // Merge the default headers. $options['headers'] += array('User-Agent' => 'Drupal (+http://drupal.org/)'); // Concessions to Guzzle. if (isset($options['data'])) { $options['body'] = $options['data']; } if (!$options['max_redirects']) { $options['allow_redirects'] = FALSE; } // Use a proxy if one is defined and the host is not on the excluded list. $proxy_server = variable_get('proxy_server', ''); if ($proxy_server && _drupal_http_use_proxy($uri['host'])) { // Set the scheme so we open a socket to the proxy server. $uri['scheme'] = 'proxy'; // Set the path to be the full URL. $uri['path'] = $url; // Since the URL is passed as the path, we won't use the parsed query. unset($uri['query']); // Add in username and password to Proxy-Authorization header if needed. if ($proxy_username = variable_get('proxy_username', '')) { $proxy_password = variable_get('proxy_password', ''); $options['headers']['Proxy-Authorization'] = 'Basic ' . base64_encode($proxy_username . (!empty($proxy_password) ? ":" . $proxy_password : '')); } // Some proxies reject requests with any User-Agent headers, while others // require a specific one. $proxy_user_agent = variable_get('proxy_user_agent', ''); // The default value matches neither condition. if ($proxy_user_agent === NULL) { unset($options['headers']['User-Agent']); } elseif ($proxy_user_agent) { $options['headers']['User-Agent'] = $proxy_user_agent; } } // Make sure the socket opened properly. // @todo Migrate error checking. // If the server URL has a user then attempt to use basic authentication. // @todo Migrate authentication. // If the database prefix is being used by SimpleTest to run the tests in a copied // database then set the user-agent header to the database prefix so that any // calls to other Drupal pages will run the SimpleTest prefixed database. The // user-agent is used to ensure that multiple testing sessions running at the // same time won't interfere with each other as they would if the database // prefix were stored statically in a file or database variable. $test_info =& $GLOBALS['drupal_test_info']; if (!empty($test_info['test_run_id'])) { $options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']); } // Calculate how much time is left of the original timeout value. $timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000; if ($timeout > 0) { /** @see \Guzzle\Http\StaticClient::request() */ static $client; if (!$client) { $client = new \Guzzle\Http\Client(); } $request = $client->createRequest($options['method'], $url, null, null, $options); if ($options['max_redirects']) { $client->getConfig()->set('redirect.max', $options['max_redirects']); } if (isset($options['stream'])) { if ($options['stream'] instanceof \Guzzle\Stream\StreamRequestFactoryInterface) { $response = $options['stream']->fromRequest($request); } elseif ($options['stream'] == true) { $streamFactory = new \Guzzle\Stream\PhpStreamRequestFactory(); $response = $streamFactory->fromRequest($request); } } else { $response = $request->send(); } $result->request = $request->__toString(); } else { $result->code = HTTP_REQUEST_TIMEOUT; $result->error = 'request timed out'; return $result; } if (isset($response)) { // Parse response headers from the response body. // Be tolerant of malformed HTTP responses that separate header and body with // \n\n or \r\r instead of \r\n\r\n. $result->data = $response->getBody(true); // Parse the response status line. $result->protocol = $response->getProtocol() . '/' . $response->getProtocolVersion(); $result->status_message = $response->getReasonPhrase(); $result->headers = array_map(function ($input) { return (string) $input; }, $response->getHeaders()->getAll()); $result->code = $response->getStatusCode(); switch ($result->code) { case 200: // OK // OK case 304: // Not modified break; case 301: // Moved permanently // Moved permanently case 302: // Moved temporarily // Moved temporarily case 307: // Moved temporarily // $result->redirect_code = $code; // $result->redirect_url = $location; break; default: $result->error = $response->getReasonPhrase(); } } return $result; }
/** * @param $import * @param bool $output */ public function heres_the_beef($import, $output = true) { global $wpdb; $api = pods_api(); for ($i = 0; $i < 40000; $i++) { echo " \t"; // extra spaces } $default_data = array('pod' => null, 'table' => null, 'reset' => null, 'update_on' => null, 'where' => null, 'fields' => array(), 'row_filter' => null, 'pre_save' => null, 'post_save' => null, 'sql' => null, 'sort' => null, 'limit' => null, 'page' => null, 'output' => null, 'page_var' => 'ipg', 'bypass_helpers' => false); $default_field_data = array('field' => null, 'filter' => null); if (!is_array($import)) { $import = array($import); } elseif (empty($import)) { die('<h1 style="color:red;font-weight:bold;">ERROR: No imports configured</h1>'); } $import_counter = 0; $total_imports = count($import); $paginated = false; $avg_time = -1; $total_time = 0; $counter = 0; $avg_unit = 100; $avg_counter = 0; foreach ($import as $datatype => $data) { $import_counter++; flush(); @ob_end_flush(); usleep(50000); if (!is_array($data)) { $datatype = $data; $data = array('table' => $data); } if (isset($data[0])) { $data = array('table' => $data[0]); } $data = array_merge($default_data, $data); if (null === $data['pod']) { $data['pod'] = array('name' => $datatype); } if (false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - <em>" . $data['pod']['name'] . "</em> - <strong>Loading Pod: " . $data['pod']['name'] . "</strong>\n"; } if (2 > count($data['pod'])) { $data['pod'] = $api->load_pod(array('name' => $data['pod']['name'])); } if (empty($data['pod']['fields'])) { continue; } if (null === $data['table']) { $data['table'] = $data['pod']['name']; } if ($data['reset'] === true) { if (false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - <strong style='color:blue;'>Resetting Pod: " . $data['pod']['name'] . "</strong>\n"; } $api->reset_pod(array('id' => $data['pod']['id'], 'name' => $data['pod']['name'])); } if (null === $data['sort'] && null !== $data['update_on'] && isset($data['fields'][$data['update_on']])) { if (isset($data['fields'][$data['update_on']]['field'])) { $data['sort'] = $data['fields'][$data['update_on']]['field']; } else { $data['sort'] = $data['update_on']; } } $page = 1; if (false !== $data['page_var'] && isset($_GET[$data['page_var']])) { $page = absval($_GET[$data['page_var']]); } if (null === $data['sql']) { $data['sql'] = "SELECT * FROM {$data['table']}" . (null !== $data['where'] ? " WHERE {$data['where']}" : '') . (null !== $data['sort'] ? " ORDER BY {$data['sort']}" : '') . (null !== $data['limit'] ? " LIMIT " . (1 < $page ? ($page - 1) * $data['limit'] . ',' : '') . "{$data['limit']}" : ''); } if (false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - Getting Results: " . $data['pod']['name'] . "\n"; } if (false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - Using Query: <small><code>" . $data['sql'] . "</code></small>\n"; } $result = $wpdb->get_results($data['sql'], ARRAY_A); if (false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - Results Found: " . count($result) . "\n"; } $avg_time = -1; $total_time = 0; $counter = 0; $avg_unit = 100; $avg_counter = 0; $result_count = count($result); $paginated = false; if (false !== $data['page_var'] && $result_count == $data['limit']) { $paginated = "<input type=\"button\" onclick=\"document.location=\\'" . pods_ui_var_update(array($data['page_var'] => $page + 1), false, false) . "\\';\" value=\" Continue Import » \" />"; } if ($result_count < $avg_unit && 5 < $result_count) { $avg_unit = number_format($result_count / 5, 0, '', ''); } elseif (2000 < $result_count && 10 < count($data['pod']['fields'])) { $avg_unit = 40; } $data['count'] = $result_count; timer_start(); if (false !== $output && 1 == $import_counter) { echo "<div style='width:50%;background-color:navy;padding:10px 10px 30px 10px;color:#FFF;position:absolute;top:10px;left:25%;text-align:center;'><p id='progress_status' align='center'>" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - Running Importer..</p><br /><small>This will automatically update every " . $avg_unit . " rows</small></div>\n"; } foreach ($result as $k => $row) { flush(); @ob_end_flush(); usleep(50000); if (false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - Processing Row #" . ($k + 1) . "\n"; } if (null !== $data['row_filter'] && function_exists($data['row_filter'])) { if (false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - Filtering <strong>" . $data['row_filter'] . "</strong> on Row #" . ($k + 1) . "\n"; } $row = $data['row_filter']($row, $data); } if (!is_array($row)) { continue; } $params = array('datatype' => $data['pod']['name'], 'columns' => array(), 'bypass_helpers' => $data['bypass_helpers']); foreach ($data['pod']['fields'] as $fk => $field_info) { $field = $field_info['name']; if (!empty($data['fields']) && !isset($data['fields'][$field]) && !in_array($field, $data['fields'])) { continue; } if (isset($data['fields'][$field])) { if (is_array($data['fields'][$field])) { $field_data = $data['fields'][$field]; } else { $field_data = array('field' => $data['fields'][$field]); } } else { $field_data = array(); } if (!is_array($field_data)) { $field = $field_data; $field_data = array(); } $field_data = array_merge($default_field_data, $field_data); if (null === $field_data['field']) { $field_data['field'] = $field; } $data['fields'][$field] = $field_data; $value = ''; if (isset($row[$field_data['field']])) { $value = $row[$field_data['field']]; } if (null !== $field_data['filter']) { if (function_exists($field_data['filter'])) { if (false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - Filtering <strong>" . $field_data['filter'] . "</strong> on Field: " . $field . "\n"; } $value = $field_data['filter']($value, $row, $data); } else { $value = ''; } } if (1 > strlen($value) && 1 == $field_info['required']) { die('<h1 style="color:red;font-weight:bold;">ERROR: Field Required for <strong>' . $field . '</strong></h1>'); } $params['columns'][$field] = $value; unset($value); unset($field_data); unset($field_info); unset($fk); } if (empty($params['columns'])) { continue; } $params['columns'] = pods_sanitize($params['columns']); if (null !== $data['update_on'] && isset($params['columns'][$data['update_on']])) { if (false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - Checking for Existing Item\n"; } $check = new Pod($data['pod']['name']); $check->findRecords(array('orderby' => 't.id', 'limit' => 1, 'where' => "t.{$data['update_on']} = '{$params['columns'][$data['update_on']]}'", 'search' => false, 'page' => 1)); if (0 < $check->getTotalRows()) { $check->fetchRecord(); $params['tbl_row_id'] = $check->get_field('id'); $params['pod_id'] = $check->get_pod_id(); if (false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - Found Existing Item w/ ID: " . $params['tbl_row_id'] . "\n"; } unset($check); } if (!isset($params['tbl_row_id']) && false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - Existing item not found - Creating New\n"; } } if (null !== $data['pre_save'] && function_exists($data['pre_save'])) { if (false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - Running Pre Save <strong>" . $data['pre_save'] . "</strong> on " . $data['pod']['name'] . "\n"; } $params = $data['pre_save']($params, $row, $data); } $id = $api->save_pod_item($params); if (false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - <strong>Saved Row #" . ($k + 1) . " w/ ID: " . $id . "</strong>\n"; } $params['tbl_row_id'] = $id; if (null !== $data['post_save'] && function_exists($data['post_save'])) { if (false !== $output) { echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - Running Post Save <strong>" . $data['post_save'] . "</strong> on " . $data['pod']['name'] . "\n"; } $data['post_save']($params, $row, $data); } unset($params); unset($result[$k]); unset($row); wp_cache_flush(); $wpdb->queries = array(); $avg_counter++; $counter++; if ($avg_counter == $avg_unit && false !== $output) { $avg_counter = 0; $avg_time = timer_stop(0, 10); $total_time += $avg_time; $rows_left = $result_count - $counter; $estimated_time_left = $total_time / $counter * $rows_left / 60; $percent_complete = 100 - $rows_left * 100 / $result_count; echo "<script type='text/javascript'>document.getElementById('progress_status').innerHTML = '" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em><br /><strong>" . $percent_complete . "% Complete</strong><br /><strong>Estimated Time Left:</strong> " . $estimated_time_left . " minute(s) or " . $estimated_time_left / 60 . " hours(s)<br /><strong>Time Spent:</strong> " . $total_time / 60 . " minute(s)<br /><strong>Rows Done:</strong> " . ($result_count - $rows_left) . "/" . $result_count . "<br /><strong>Rows Left:</strong> " . $rows_left . "';</script>\n"; echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - <strong>Updated Status:</strong> " . $percent_complete . "% Complete</strong>\n"; } } if (false !== $output) { $avg_counter = 0; $avg_time = timer_stop(0, 10); $total_time += $avg_time; $rows_left = $result_count - $counter; $estimated_time_left = $total_time / $counter * $rows_left / 60; $percent_complete = 100 - $rows_left * 100 / $result_count; echo "<script type='text/javascript'>document.getElementById('progress_status').innerHTML = '" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em><br /><strong style=\\'color:green;\\'>100% Complete</strong><br /><br /><strong>Time Spent:</strong> " . $total_time / 60 . " minute(s)<br /><strong>Rows Imported:</strong> " . $result_count . (false !== $paginated ? "<br /><br />" . $paginated : '') . "';</script>\n"; echo "<br />" . date('Y-m-d h:i:sa') . " - <em>" . $data['pod']['name'] . "</em> - <strong style='color:green;'>Done Importing: " . $data['pod']['name'] . "</strong>\n"; } unset($result); unset($import[$datatype]); unset($datatype); unset($data); wp_cache_flush(); $wpdb->queries = array(); } if (false !== $output) { $avg_counter = 0; $avg_time = timer_stop(0, 10); $total_time += $avg_time; $rows_left = $result_count - $counter; echo "<script type='text/javascript'>document.getElementById('progress_status').innerHTML = '" . date('Y-m-d h:i:sa') . " - <strong style=\\'color:green;\\'>Import Complete</strong><br /><br /><strong>Time Spent:</strong> " . $total_time / 60 . " minute(s)<br /><strong>Rows Imported:</strong> " . $result_count . (false !== $paginated ? "<br /><br />" . $paginated : '') . "';</script>\n"; echo "<br />" . date('Y-m-d h:i:sa') . " - <strong style='color:green;'>Import Complete</strong>\n"; } }
function wp_mail_receive() { global $img_target; require_once wp_base() . '/wp-includes/class-pop3.php'; timer_start(); $use_cache = 1; $time_difference = get_settings('time_difference'); error_reporting(2037); $GLOBALS['wp_pop3'] = new POP3(); if (!$GLOBALS['wp_pop3']->connect(get_settings('mailserver_url'), get_settings('mailserver_port'))) { echo "Ooops {$GLOBALS['wp_pop3']}->ERROR <br />\n"; return; } $mail_count = $GLOBALS['wp_pop3']->login(get_settings('mailserver_login'), get_settings('mailserver_pass')); if ($mail_count == false) { if (!$GLOBALS['wp_pop3']->FP) { echo "Oooops Login Failed: {$wp_pop3->ERROR}<br />\n"; } else { echo "No Message<br />\n"; $GLOBALS['wp_pop3']->quit(); } return; } // ONLY USE THIS IF YOUR PHP VERSION SUPPORTS IT! register_shutdown_function('wp_mail_quit'); for ($mail_num = 1; $mail_num <= $mail_count; $mail_num++) { $MsgOne = $GLOBALS['wp_pop3']->get($mail_num); if (!$MsgOne || gettype($MsgOne) != 'array') { echo "oops, {$GLOBALS['wp_pop3']}->ERROR<br />\n"; $GLOBALS['wp_pop3']->quit(); return; } $content = ''; $content_type = ''; $boundary = ''; $alt_boundary = ''; $emb_boundary = ''; $dmonths = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); $mailMsg = ''; while (list($lineNum, $line) = each($MsgOne)) { $mailMsg .= $line; } $mailParts = parse_msg($mailMsg); if (!empty($mailParts['header']['date'])) { $ddate = trim($mailParts['header']['date'][0]); if (strpos($ddate, ',')) { $ddate = trim(substr($ddate, strpos($ddate, ',') + 1, strlen($ddate))); } $ddate_U = strtotime($ddate) + $time_difference * 3600; $post_date = date('Y-m-d H:i:s', $ddate_U); } if (!empty($mailParts['header']['subject'])) { $subject = trim($mailParts['header']['subject'][0]); if (function_exists('mb_decode_mimeheader')) { $subject1 = mb_decode_mimeheader($subject); if ($subject1 != $subject) { $sub_charset = mb_internal_encoding(); } else { $sub_charset = "auto"; } $subject = $subject1; } if (get_settings('use_phoneemail')) { $subject = explode(get_settings('phoneemail_separator'), $subject); $subject = trim($subject[0]); } } if (!ereg(get_settings('subjectprefix'), $subject)) { continue; } $charset = ""; $ncharset = preg_match("/\\s?charset=\"?([A-Za-z0-9\\-]*)\"?/i", $content, $matches); if ($ncharset) { $charset = $matches[1]; } $ddate_today = time() + $time_difference * 3600; $ddate_difference_days = ($ddate_today - $ddate_U) / 86400; if ($ddate_difference_days > 14) { echo "Too old<br />\n"; continue; } if (preg_match('/' . get_settings('subjectprefix') . '/', $subject)) { $userpassstring = ''; echo "<div style=\"border: 1px dashed #999; padding: 10px; margin: 10px;\">\n"; echo "<p><b>{$mail_num}</b></p><p><b>Subject: </b>{$subject}</p>\n"; $subject = trim(str_replace(get_settings('subjectprefix'), '', $subject)); $attaches = array(); if ($mailParts['type'] == 'multipart') { if ($mailParts['subtype'] == 'mixed') { for ($i = 1; $i < count($mailParts['body']); $i++) { $attaches[] = array('type' => 'mix', 'body' => $mailParts['body'][$i]); } if (!is_array($mailParts['body'][0]['body'])) { $content = $mailParts['body'][0]['body']; $charset = $mailParts['body'][0]['charset']; $encoding = $mailParts['body'][0]['encodings']; $content = convert_content($content, $charest, $encoding); } else { $mailParts = $mailParts['body'][0]; } } if ($mailParts['type'] == 'multipart' && $mailParts['subtype'] == 'related') { if ($mailParts['body'][0]['type'] == 'multipart' && $mailParts['body'][0]['subtype'] == 'alternative') { $content = $mailParts['body'][0]['body'][1]['body']; $charset = $mailParts['body'][0]['body'][1]['charset']; $encoding = $mailParts['body'][0]['body'][1]['encodings']; $content = convert_content($content, $charest, $encoding); } else { $content = $mailParts['body'][0]['body']; $charset = $mailParts['body'][0]['charset']; $encoding = $mailParts['body'][0]['encodings']; $content = convert_content($content, $charest, $encoding); } $content = preg_replace('/(\\<.*?\\>)/es', 'str_replace(array("\\n","\\r"), array(" ", " "), "\\1")', $content); $content = preg_replace('/\\<head\\>.*\\<\\/head\\>/is', '', $content); $content = preg_replace('/(\\<body\\s*[^\\>]*\\>)\\s*\\<br\\s*\\/*\\>\\s*/is', '\\1', $content); $content = strip_tags($content, '<img><p><br><i><b><u><em><strong><strike><font><span><div><dl><dt><dd><ol><ul><li>,<table><tr><td><category><title>'); $content = preg_replace('!(</div>|</p>)([^\\r\\n])!i', "\\1\n\\2", $content); for ($i = 1; $i < count($mailParts['body']); $i++) { $attaches[] = array('type' => 'relate', 'body' => $mailParts['body'][$i], 'id' => preg_replace('/<(.*)>/', '$1', $mailParts['body'][$i]['header']['content-id'][0])); } } if ($mailParts['type'] == 'multipart' && $mailParts['subtype'] == 'alternative') { if ($mailParts['body'][1]['type'] == 'multipart' && $mailParts['body'][1]['subtype'] == 'related') { $content = $mailParts['body'][1]['body'][0]['body']; $charset = $mailParts['body'][1]['body'][0]['charset']; $encoding = $mailParts['body'][1]['body'][0]['encodings']; $content = convert_content($content, $charest, $encoding); for ($i = 1; $i < count($mailParts['body'][1]['body']); $i++) { $attaches[] = array('type' => 'relate', 'body' => $mailParts['body'][1]['body'][$i], 'id' => preg_replace('/<(.*)>/', '$1', $mailParts['body'][1]['body'][$i]['header']['content-id'][0])); } } else { $content = $mailParts['body'][1]['body']; $charset = $mailParts['body'][1]['charset']; $encoding = $mailParts['body'][1]['encodings']; $content = convert_content($content, $charest, $encoding); } $content = preg_replace('/(\\<[^\\>]*\\>)/es', 'str_replace(array("\\n","\\r"), array(" ", " "), "\\1")', $content); $content = preg_replace('/\\<head\\>.*\\<\\/head\\>/is', '', $content); $content = preg_replace('/(\\<body\\s*[^\\>]*\\>)\\s*\\<br\\s*\\/*\\>\\s*/is', '\\1', $content); $content = strip_tags($content, '<img><p><br><i><b><u><em><strong><strike><font><span><div><dl><dt><dd><ol><ul><li>,<table><tr><td><category><title>'); $content = preg_replace('!(</div>|</p>)([^\\r\\n])!i', "\\1\n\\2", $content); } } else { $content = $mailParts['body']; $charset = $mailParts['charset']; $encoding = $mailParts['encodings']; $content = convert_content($content, $charest, $encoding); } $content = trim($content); echo "<p><b>Content-type:</b> {$content_type}, <b>boundary:</b> {$boundary}</p>\n"; echo "<p><b>alt_boundary:</b> {$alt_boundary}, <b>emb_boundary:</b> {$emb_boundary}</p>\n"; echo "<p><b>charset:</b>{$charset}, <b>BLOG charset:</b>" . $GLOBALS['blog_charset'] . "</p>\n"; // echo "<p><b>Raw content:</b><br /><pre>".$content.'</pre></p>'; if ($charset == "" || trim(strtoupper($charset)) == "ISO-2022-JP") { $charset = "JIS"; } if (trim(strtoupper($charset)) == "SHIFT_JIS") { $charset = "SJIS"; } $btpos = strpos($content, get_settings('bodyterminator')); if ($btpos) { $content = substr($content, 0, $btpos); } $content = trim($content); $blah = explode("\n", preg_replace("/^[\n\r\\s]*/", "", strip_tags($content))); $firstline = preg_replace("/[\n\r]/", "", $blah[0]); $secondline = $blah[1]; if (get_settings('use_phoneemail')) { echo "<p><b>Use Phone Mail:</b> Yes</p>\n"; $btpos = strpos($firstline, get_settings('phoneemail_separator')); if ($btpos) { $userpassstring = trim(substr($firstline, 0, $btpos)); $content = trim(substr($content, $btpos + strlen(get_settings('phoneemail_separator')), strlen($content))); $btpos = strpos($content, get_settings('phoneemail_separator')); if ($btpos) { $userpassstring = trim(substr($content, 0, $btpos)); $content = trim(substr($content, $btpos + strlen(get_settings('phoneemail_separator')), strlen($content))); } } $contentfirstline = $blah[1]; } else { echo "<p><b>Use Phone Mail:</b> No</p>\n"; $userpassstring = strip_tags($firstline); $contentfirstline = ''; } $flat = 999.0; $flon = 999.0; $secondlineParts = explode(':', strip_tags($secondline)); if (strncmp($secondlineParts[0], "POS", 3) == 0) { echo "Found POS:<br />\n"; // echo "Second parts is:".$secondlineParts[1]; // the second line is the postion listing line $secLineParts = explode(',', $secondlineParts[1]); $flatStr = $secLineParts[0]; $flonStr = $secLineParts[1]; // echo "String are ".$flatStr.$flonStr; $flat = floatval($secLineParts[0]); $flon = floatval($secLineParts[1]); // echo "values are ".$flat." and ".$flon; // ok remove that position... we should not have it in the final output $content = str_replace($secondline, '', $content); } $blah = explode(':', $userpassstring); $user_login = trim($blah[0]); $user_pass = $blah[1]; $content = $contentfirstline . str_replace($firstline, '', $content); $content = trim($content); // Please uncomment following line, only if you want to check user and password. // echo "<p><b>Login:</b> $user_login, <b>Pass:</b> $user_pass</p>"; echo "<p><b>Login:</b> {$user_login}, <b>Pass:</b> *********</p>"; if (!user_pass_ok($user_login, $user_pass)) { echo "<p><b>Error: Wrong Login.</b></p></div>\n"; continue; } $userdata = get_userdatabylogin($user_login); $user_level = $userdata->user_level; $post_author = $userdata->ID; if ($user_level > 0) { $post_title = xmlrpc_getposttitle($content); if ($post_title == '') { $post_title = $subject; } echo "Subject : " . mb_conv($post_title, $GLOBALS['blog_charset'], $sub_charset) . " <br />\n"; $post_category = get_settings('default_category'); if (preg_match('/<category>(.+?)<\\/category>/is', $content, $matchcat)) { $post_category = xmlrpc_getpostcategory($content); $content = xmlrpc_removepostdata($content); } if (empty($post_category)) { $post_category = get_settings('default_post_category'); } echo "Category : {$post_category} <br />\n"; $post_category = explode(',', $post_category); if (!get_settings('emailtestonly')) { $content = preg_replace('|\\n([^\\n])|', " \$1", trim($content)); $content_before = ""; $content_after = ""; for ($i = 0; $i < count($attaches); $i++) { $create_thumbs = $attaches[$i]['type'] == 'mix' ? 1 : 0; list($file_name, $is_img, $orig_name) = wp_getattach($attaches[$i]['body'], "user-" . trim($post_author), $create_thumbs); if ($file_name) { if ($attaches[$i]['type'] == 'relate') { $content = preg_replace("/cid:" . preg_quote($attaches[$i]['id']) . "/", get_settings('fileupload_url') . '/' . $file_name, $content); } else { if (isset($img_target) && $img_target) { $img_target = ' target="' . $img_target . '"'; } else { $img_target = ''; } if ($is_img) { if (file_exists(get_settings('fileupload_realpath') . "/thumb-" . $file_name)) { $content_before .= "<a href=\"" . get_settings('fileupload_url') . '/' . rawurlencode($file_name) . "\"" . $img_target . "><img style=\"float: left;\" hspace=\"6\" src=\"" . get_settings('fileupload_url') . '/thumb-' . rawurlencode($file_name) . "\" alt=\"" . $orig_name . "\" title=\"" . $orig_name . "\" /></a>"; } else { $content_before .= "<a href=\"" . get_settings('fileupload_url') . '/' . rawurlencode($file_name) . "\"" . $img_target . "><img style=\"float: left;\" hspace=\"6\" src=\"" . get_settings('fileupload_url') . '/' . rawurlencode($file_name) . "\" alt=\"" . $orig_name . "\" title=\"" . $orig_name . "\" /></a>"; } } else { $content_after .= "<a href=\"" . wp_siteurl() . "/wp-download.php?from=" . rawurlencode($file_name) . "&fname=" . urlencode($orig_name) . "\"" . $img_target . "><img style=\"float: left;\" hspace=\"6\" src=\"" . wp_siteurl() . "/wp-images/file.gif\" alt=\"" . $orig_name . "\" title=\"" . $orig_name . "\" />" . $orig_name . "</a>"; } } } } $content = $content_before . $content . "<br clear=\"left\" />" . $content_after; $postHandler =& wp_handler('Post'); $postObject =& $postHandler->create(); $postObject->setVar('post_content', $content, true); $postObject->setVar('post_title', trim(mb_conv($post_title, $GLOBALS['blog_charset'], $sub_charset)), true); $postObject->setVar('post_date', $post_date, true); $postObject->setVar('post_author', $post_author, true); $postObject->setVar('post_category', $post_category[0], true); $postObject->setVar('post_name', sanitize_title($post_title), true); if ($flat < 500) { $postObject->setVar('post_lat', $flat, true); $postObject->setVar('post_lon', $flon, true); } $postObject->setVar('post_status', get_settings('default_post_status'), true); $postObject->setVar('ping_status', get_settings('default_ping_status'), true); $postObject->setVar('comment_status', get_settings('default_comment_status'), true); if (!$postHandler->insert($postObject, true)) { echo "<b>Error: Insert New Post</b><br />"; } $post_ID = $postObject->getVar('ID'); echo "Post ID = {$post_ID}<br />\n"; $postObject->assignCategories($post_category, true); do_action('publish_post', $post_ID); do_action('publish_phone', $post_ID); if ($flat < 500) { pingGeoUrl($post_ID); } $blog_ID = 1; pingWeblogs($blog_ID); pingback($content, $post_ID); } echo "\n<p><b>Posted title:</b> {$post_title}<br />\n"; echo "<b>Posted content:</b><br /><pre>" . $content . "</pre></p>\n"; if (!$GLOBALS['wp_pop3']->delete($mail_num)) { echo "<p>Oops " . $GLOBALS['wp_pop3']->ERROR . "</p></div>\n"; $GLOBALS['wp_pop3']->reset(); return; } else { echo "<p>Mission complete, message <strong>{$mail_num}</strong> deleted.</p>\n"; } } else { echo "<p><strong>Level 0 users can\\'t post.</strong></p>\n"; } echo "</div>\n"; } } $GLOBALS['wp_pop3']->quit(); timer_stop($GLOBALS['wp_mail_debug']); return; }
function wp_rss_multi_importer_shortcode($atts = array()) { add_action('wp_footer', 'footer_scripts'); if (!function_exists("wprssmi_hourly_feed")) { function wprssmi_hourly_feed() { return 0; } } add_filter('wp_feed_cache_transient_lifetime', 'wprssmi_hourly_feed'); $siteurl = get_site_url(); $cat_options_url = $siteurl . '/wp-admin/options-general.php?page=wp_rss_multi_importer_admin&tab=category_options/'; $images_url = $siteurl . '/wp-content/plugins/' . basename(dirname(__FILE__)) . '/images'; global $fopenIsSet; $fopenIsSet = ini_get('allow_url_fopen'); $parms = shortcode_atts(array('category' => 0, 'hdsize' => '16px', 'hdweight' => 400, 'anchorcolor' => '', 'testyle' => 'color: #000000; font-weight: bold;margin: 0 0 0.8125em;', 'maximgwidth' => 150, 'datestyle' => 'font-style:italic;', 'floattype' => '', 'showdate' => 1, 'showgroup' => 1, 'thisfeed' => '', 'timer' => 0, 'dumpthis' => 0, 'cachetime' => NULL, 'pinterest' => 0, 'maxperpage' => 0, 'excerptlength' => 50, 'noimage' => 0, 'sortorder' => NULL, 'defaultimage' => NULL, 'showdesc' => NULL, 'mytemplate' => '', 'showmore' => NULL, 'authorprep' => 'by', 'windowstyle' => NULL, 'morestyle' => '[...]'), $atts); $showThisDesc = $parms['showdesc']; $defaultImage = $parms['defaultimage']; $sortOrder = $parms['sortorder']; $authorPrep = $parms['authorprep']; $anchorcolor = $parms['anchorcolor']; $datestyle = $parms['datestyle']; $hdsize = $parms['hdsize']; $thisCat = $parms['category']; $parmfloat = $parms['floattype']; $catArray = explode(",", $thisCat); $showdate = $parms['showdate']; $showgroup = $parms['showgroup']; $pshowmore = $parms['showmore']; $hdweight = $parms['hdweight']; $testyle = $parms['testyle']; global $morestyle; $morestyle = $parms['morestyle']; $warnmsg = $parms['warnmsg']; global $maximgwidth; $maximgwidth = $parms['maximgwidth']; $thisfeed = $parms['thisfeed']; // max posts per feed $timerstop = $parms['timer']; $dumpthis = $parms['dumpthis']; //diagnostic parameter $cachename = 'wprssmi_' . $thisCat; $cachetime = $parms['cachetime']; $pinterest = $parms['pinterest']; $parmmaxperpage = $parms['maxperpage']; $noimage = $parms['noimage']; $mytemplate = $parms['mytemplate']; $windowstyle = $parms['windowstyle']; $excerptlength = $parms['excerptlength']; $readable = ''; $options = get_option('rss_import_options'); $option_items = get_option('rss_import_items'); $option_category_images = get_option('rss_import_categories_images'); if ($option_items == false) { return _e("You need to set up the WP RSS Multi Importer Plugin before any results will show here. Just go into the <a href='/wp-admin/options-general.php?page=wp_rss_multi_importer_admin'>settings panel</a> and put in some RSS feeds", 'wp-rss-multi-importer'); } $cat_array = preg_grep("^feed_cat_^", array_keys($option_items)); if (count($cat_array) == 0) { // for backward compatibility $noExistCat = 1; } else { $noExistCat = 0; } if (!empty($option_items)) { //GET PARAMETERS global $RSSdefaultImage; $RSSdefaultImage = $options['RSSdefaultImage']; // 0- process normally, 1=use default for category, 2=replace when no image available $size = count($option_items); $sortDir = $options['sortbydate']; // 1 is ascending $stripAll = $options['stripAll']; $todaybefore = $options['todaybefore']; $adjustImageSize = $options['adjustImageSize']; $showDesc = $options['showdesc']; // 1 is show $descNum = $options['descnum']; $maxperPage = $options['maxperPage']; $showcategory = $options['showcategory']; $cacheMin = $options['cacheMin']; $maxposts = $options['maxfeed']; $showsocial = $options['showsocial']; $targetWindow = $options['targetWindow']; // 0=LB, 1=same, 2=new $floatType = $options['floatType']; $noFollow = $options['noFollow']; $showmore = $options['showmore']; $cb = $options['cb']; // 1 if colorbox should not be loaded $pag = $options['pag']; // 1 if pagination $perPage = $options['perPage']; global $anyimage; $anyimage = $options['anyimage']; $addAuthor = $options['addAuthor']; $warnmsg = $options['warnmsg']; $directFetch = $options['directFetch']; $forceFeed = $options['forceFeed']; $forceFeed = $forceFeed == 1 ? True : False; $timeout = $options['timeout']; if (!isset($timeout)) { $timeout = 10; } if (!isset($directFetch)) { $directFetch = 0; } if (!is_null($defaultImage)) { $RSSdefaultImage = $defaultImage; } if (!is_null($windowstyle)) { $targetWindow = $windowstyle; } if (!is_null($showThisDesc)) { $showDesc = $showThisDesc; } if (!is_null($sortOrder)) { $sortDir = $sortOrder; } if (!is_null($pshowmore)) { $showmore = $pshowmore; } if (!is_null($excerptlength)) { $descNum = $excerptlength; } if (empty($options['sourcename'])) { $attribution = ''; } else { $attribution = $options['sourcename'] . ': '; } if ($floatType == '1') { $float = "left"; } else { $float = "none"; } if ($parmfloat != '') { $float = $parmfloat; } if ($parmmaxperpage != 0) { $maxperPage = $parmmaxperpage; } if ($noimage == 1) { $stripAll = 1; } if ($thisfeed != '') { $maxposts = $thisfeed; } if ($pinterest == 1) { $divfloat = "left"; } else { $divfloat = ''; } if ($cacheMin == '') { $cacheMin = 0; } //set caching minutes if (!is_null($cachetime)) { $cacheMin = $cachetime; } //override caching minutes with shortcode parameter if (is_null($cb) && $targetWindow == 0) { add_action('wp_footer', 'colorbox_scripts'); // load colorbox only if not indicated as conflict } $template = $options['template']; if ($mytemplate != '') { $template = $mytemplate; } // END PARAMETERS timer_start(); //TIMER START - for testing purposes $myarray = get_transient($cachename); // added for transient cache if ($cacheMin == 0) { delete_transient($cachename); } if (false === $myarray) { // added for transient cache - only get feeds and put into array if the array isn't cached (for a given category set) for ($i = 1; $i <= $size; $i = $i + 1) { $key = key($option_items); if (!strpos($key, '_') > 0) { continue; } //this makes sure only feeds are included here...everything else are options $rssName = $option_items[$key]; next($option_items); $key = key($option_items); $rssURL = $option_items[$key]; next($option_items); $key = key($option_items); $rssCatID = $option_items[$key]; ///this should be the category ID if (!in_array(0, $catArray) && in_array($option_items[$key], $catArray) || in_array(0, $catArray) || $noExistCat == 1) { $myfeeds[] = array("FeedName" => $rssName, "FeedURL" => $rssURL, "FeedCatID" => $rssCatID); //with Feed Category ID } $cat_array = preg_grep("^feed_cat_^", array_keys($option_items)); // for backward compatibility if (count($cat_array) > 0) { next($option_items); //skip feed category } } if ($maxposts == "") { return _e("One more step...go into the the <a href='/wp-admin/options-general.php?page=wp_rss_multi_importer_admin&tab=setting_options'>Settings Panel and choose Options.</a>", 'wp-rss-multi-importer'); } // check to confirm they set options if (empty($myfeeds)) { return _e("You've either entered a category ID that doesn't exist or have no feeds configured for this category. Edit the shortcode on this page with a category ID that exists, or <a href=" . $cat_options_url . ">go here and and get an ID</a> that does exist in your admin panel.", 'wp-rss-multi-importer'); exit; } if ($dumpthis == 1) { rssmi_list_the_plugins(); echo "<strong>Feeds</strong><br>"; var_dump($myfeeds); } foreach ($myfeeds as $feeditem) { $url = (string) $feeditem["FeedURL"]; while (stristr($url, 'http') != $url) { $url = substr($url, 1); } if (empty($url)) { continue; } $url = esc_url_raw(strip_tags($url)); if ($directFetch == 1) { $feed = wp_rss_fetchFeed($url, $timeout, $forceFeed); } else { $feed = fetch_feed($url); } if (is_wp_error($feed)) { if ($dumpthis == 1) { echo $feed->get_error_message(); } if ($size < 4) { return _e("You have one feed and it's not a valid RSS feed. This is likely a problem with the source of the RSS feed. Contact our support forum for help.", 'wp-rss-multi-importer'); exit; } else { //echo $feed->get_error_message(); continue; } } $maxfeed = $feed->get_item_quantity(0); if ($feedAuthor = $feed->get_author()) { $feedAuthor = $feed->get_author()->get_name(); } //SORT DEPENDING ON SETTINGS if ($sortDir == 1) { for ($i = $maxfeed - 1; $i >= $maxfeed - $maxposts; $i--) { $item = $feed->get_item($i); if (empty($item)) { continue; } if (include_post($feeditem["FeedCatID"], $item->get_content(), $item->get_title()) == 0) { continue; } // FILTER if ($enclosure = $item->get_enclosure()) { if (!IS_NULL($item->get_enclosure()->get_thumbnail())) { $mediaImage = $item->get_enclosure()->get_thumbnail(); } else { if (!IS_NULL($item->get_enclosure()->get_link())) { $mediaImage = $item->get_enclosure()->get_link(); } } } if ($itemAuthor = $item->get_author()) { $itemAuthor = $item->get_author()->get_name(); } else { if (!IS_NULL($feedAuthor)) { $itemAuthor = $feedAuthor; } } $myarray[] = array("mystrdate" => strtotime($item->get_date()), "mytitle" => $item->get_title(), "mylink" => $item->get_link(), "myGroup" => $feeditem["FeedName"], "mydesc" => $item->get_content(), "myimage" => $mediaImage, "mycatid" => $feeditem["FeedCatID"], "myAuthor" => $itemAuthor); unset($mediaImage); unset($itemAuthor); } } else { for ($i = 0; $i <= $maxposts - 1; $i++) { $item = $feed->get_item($i); if (empty($item)) { continue; } if (include_post($feeditem["FeedCatID"], $item->get_content(), $item->get_title()) == 0) { continue; } // FILTER // $x=1; if ($enclosure = $item->get_enclosure()) { if (!IS_NULL($item->get_enclosure()->get_thumbnail())) { $mediaImage = $item->get_enclosure()->get_thumbnail(); //$mediaImage=$mediaImage2[$x]; } else { if (!IS_NULL($item->get_enclosure()->get_link())) { $mediaImage = $item->get_enclosure()->get_link(); } } } if ($itemAuthor = $item->get_author()) { $itemAuthor = $item->get_author()->get_name(); } else { if (!IS_NULL($feedAuthor)) { $itemAuthor = $feedAuthor; } } $myarray[] = array("mystrdate" => strtotime($item->get_date()), "mytitle" => $item->get_title(), "mylink" => $item->get_link(), "myGroup" => $feeditem["FeedName"], "mydesc" => $item->get_content(), "myimage" => $mediaImage, "mycatid" => $feeditem["FeedCatID"], "myAuthor" => $itemAuthor); unset($mediaImage); unset($itemAuthor); } } } if ($cacheMin !== 0) { set_transient($cachename, $myarray, 60 * $cacheMin); // added for transient cache } } // added for transient cache if ($timerstop == 1) { timer_stop(1); echo ' seconds<br>'; //TIMER END for testing purposes } // CHECK $myarray BEFORE DOING ANYTHING ELSE // if ($dumpthis == 1) { echo "<br><strong>Array</strong><br>"; var_dump($myarray); return; } if (!isset($myarray) || empty($myarray)) { if (!$warnmsg == 1 && current_user_can('edit_post')) { return _e("There is a problem with the feeds you entered. Go to our <a href='http://www.allenweiss.com/faqs/im-told-the-feed-isnt-valid-or-working/'>support page</a> to see how to solve this.", 'wp-rss-multi-importer'); } return; } global $isMobileDevice; if (isset($isMobileDevice) && $isMobileDevice == 1) { //open mobile device windows in new tab $targetWindow = 2; } //$myarrary sorted by mystrdate foreach ($myarray as $key => $row) { $dates[$key] = $row["mystrdate"]; } //SORT, DEPENDING ON SETTINGS if ($sortDir == 1) { array_multisort($dates, SORT_ASC, $myarray); } else { array_multisort($dates, SORT_DESC, $myarray); } // HOW THE LINK OPENS if ($targetWindow == 0) { $openWindow = 'class="colorbox"'; } elseif ($targetWindow == 1) { $openWindow = 'target="_self"'; } else { $openWindow = 'target="_blank"'; } $total = -1; $todayStamp = 0; $idnum = 0; //for pagination $currentPage = trim($_REQUEST[pg]); $currentURL = $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; $currentURL = str_replace('&pg=' . $currentPage, '', $currentURL); $currentURL = str_replace('?pg=' . $currentPage, '', $currentURL); if (strpos($currentURL, '?') == 0) { $currentURL = $currentURL . '?'; } else { $currentURL = $currentURL . '&'; } //pagination controls and parameters if (!isset($perPage)) { $perPage = 5; } $numPages = ceil(count($myarray) / $perPage); if (!$currentPage || $currentPage > $numPages) { $currentPage = 0; } $start = $currentPage * $perPage; $end = $currentPage * $perPage + $perPage; if ($pag == 1) { //set up pagination array and put into myarray foreach ($myarray as $key => $val) { if ($key >= $start && $key < $end) { $pagedData[] = $myarray[$key]; } } $myarray = $pagedData; } //end set up pagination array and put into myarray // templates checked and added here if (!isset($template) || $template == '') { return _e("One more step...go into the <a href='/wp-admin/options-general.php?page=wp_rss_multi_importer_admin&tab=setting_options'>Settings Panel and choose a Template.</a>", 'wp-rss-multi-importer'); } require WP_RSS_MULTI_TEMPLATES . $template; } //pagination controls at bottom if ($pag == 1 && $numPages > 1) { $readable .= '<div class="rssmi_pagination"><ul>'; for ($q = 0; $q < $numPages; $q++) { if ($currentPage > 0 && $q == 0) { $readable .= '<li class="prev"><a href="http://' . $currentURL . 'pg=' . ($currentPage - 1) . '">Prev</a></li>'; } if ($currentPage != $q) { $readable .= '<li><a href="http://' . $currentURL . 'pg=' . $q . '"> ' . __($q + 1, 'wp-rss-multi-importer') . '</a></li>'; } else { $readable .= '<li class="active"><a href="#">' . ($q + 1) . '</a></li>'; } if ($q == $numPages - 1 && $currentPage != $numPages - 1) { $readable .= '<li class="next"><a href="http://' . $currentURL . 'pg=' . ($currentPage + 1) . '">Next</a></li>'; } } $readable .= '</ul></div>'; } //end pagination controls at bottom return $readable; }
/** * Calls a Lingotek API method. * * @return mixed * On success, a stdClass object of the returned response data, FALSE on error. */ public function request($method, $parameters = array(), $request_method = 'POST', $credentials = NULL) { global $user; LingotekLog::trace('<h2>@method</h2> (trace)', array('@method' => $method)); $response_data = FALSE; // Every v4 API request needs to have the externalID parameter present. // Defaults the externalId to the lingotek_login_id, unless externalId is passed as a parameter if (!isset($parameters['externalId'])) { $parameters['externalId'] = variable_get('lingotek_login_id', ''); } module_load_include('php', 'lingotek', 'lib/oauth-php/library/OAuthStore'); module_load_include('php', 'lingotek', 'lib/oauth-php/library/OAuthRequester'); $credentials = is_null($credentials) ? array('consumer_key' => variable_get('lingotek_oauth_consumer_id', ''), 'consumer_secret' => variable_get('lingotek_oauth_consumer_secret', '')) : $credentials; $timer_name = $method . '-' . microtime(TRUE); timer_start($timer_name); $response = NULL; try { OAuthStore::instance('2Leg', $credentials); $api_url = $this->api_url . '/' . $method; $request = @new OAuthRequester($api_url, $request_method, $parameters); // There is an error right here. The new OAuthRequester throws it, because it barfs on $parameters // The error: Warning: rawurlencode() expects parameter 1 to be string, array given in OAuthRequest->urlencode() (line 619 of .../modules/lingotek/lib/oauth-php/library/OAuthRequest.php). // The thing is, if you encode the params, they just get translated back to an array by the object. They have some type of error internal to the object code that is handling things wrong. // I couldn't find a way to get around this without changing the library. For now, I am just supressing the warning w/ and @ sign. $result = $request->doRequest(0, array(CURLOPT_SSL_VERIFYPEER => FALSE)); $response = $method == 'downloadDocument' ? $result['body'] : json_decode($result['body']); } catch (OAuthException2 $e) { LingotekLog::error('Failed OAuth request. <br />API URL: @url <br />Message: @message. <br />Method: @name. <br />Parameters: !params. <br />Response: !response', array('@url' => $api_url, '@message' => $e->getMessage(), '@name' => $method, '!params' => $parameters, '!response' => $response), 'api'); } $timer_results = timer_stop($timer_name); $message_params = array('@url' => $api_url, '@method' => $method, '!params' => $parameters, '!request' => $request, '!response' => $method == 'downloadDocument' ? 'Zipped Lingotek Document Data' : $response, '@response_time' => number_format($timer_results['time']) . ' ms'); /* Exceptions: downloadDocument - Returns misc data (no $response->results), and should always be sent back. assignProjectManager - Returns fails/falses if the person is already a community manager (which should be ignored) */ if ($method == 'downloadDocument' || $method == 'assignProjectManager' || !is_null($response) && $response->results == self::RESPONSE_STATUS_SUCCESS) { LingotekLog::info('<h1>@method</h1> <strong>API URL:</strong> @url <br /><strong>Response Time:</strong> @response_time<br /><strong>Request Params</strong>: !params<br /><strong>Response:</strong> !response<br/><strong>Full Request:</strong> !request', $message_params, 'api'); $response_data = $response; } else { LingotekLog::error('<h1>@method (Failed)</h1> <strong>API URL:</strong> @url <br /><strong>Response Time:</strong> @response_time<br /><strong>Request Params</strong>: !params<br /><strong>Response:</strong> !response<br/><strong>Full Request:</strong> !request', $message_params, 'api'); } return $response_data; }
function meiu_bootstrap() { unset_globals(); global $base_url, $base_path, $base_root, $language, $templatelangs; timer_start('page'); require_once COREDIR . 'loader.php'; require_once INCDIR . 'functions.php'; include_once INCDIR . 'plugin.php'; init_defines(); if (file_exists(COREDIR . 'lang' . DIRECTORY_SEPARATOR . LANGSET . '.lang.php')) { require_once COREDIR . 'lang' . DIRECTORY_SEPARATOR . LANGSET . '.lang.php'; } boot_init(); $plugin =& loader::lib('plugin'); $Config =& loader::config(); if (!$Config['safemode']) { $plugin->init_plugins(); } $plugin->trigger('boot_init'); //输出对象 $output =& loader::lib('output'); //载入当前用户信息 $user =& loader::model('user'); $output->set('loggedin', $user->loggedin()); if ($user->loggedin()) { $output->set('u_info', $user->get_all_field()); $user_extrainfo = $user->get_extra($user->get_field('id')); $output->set('u_extrainfo', $user_extrainfo); $user_theme = isset($user_extrainfo['theme']) ? $user_extrainfo['theme'] : ''; } else { $user_theme = null; } init_template($user_theme); $templatelangs = array(); $uri =& loader::lib('uri'); $uriinfo = $uri->parse_uri(); $setting_mdl =& loader::model('setting'); //如果数据库中的版本和程序版本不一致则跳转到执行自动升级脚本 $version = $setting_mdl->get_conf('system.version'); if ($version != MPIC_VERSION) { if (file_exists(ROOTDIR . 'install/upgrade.php')) { include ROOTDIR . 'install/upgrade.php'; exit; } } $output->set('base_path', $base_path); $output->set('statics_path', $base_path . 'statics/'); $output->set('site_logo', $setting_mdl->get_conf('site.logo', '')); $output->set('site_name', $setting_mdl->get_conf('site.title', lang('myalbum'))); define('IN_CTL', $uriinfo['ctl']); define('IN_ACT', $uriinfo['act']); $_GET = array_merge($_GET, $uriinfo['pars']); $_REQUEST = array_merge($_REQUEST, $uriinfo['pars']); require_once INCDIR . 'pagecore.php'; if ($plugin->has_trigger('custom_page.' . IN_CTL . '.' . IN_ACT) || $plugin->has_trigger('custom_page.' . IN_CTL)) { $plugin->trigger('custom_page.' . IN_CTL . '.' . IN_ACT) || $plugin->trigger('custom_page.' . IN_CTL, IN_ACT); } else { if (file_exists(CTLDIR . $uriinfo['ctl'] . '.ctl.php')) { require_once CTLDIR . $uriinfo['ctl'] . '.ctl.php'; $controller_name = $uriinfo['ctl'] . '_ctl'; $controller = new $controller_name(); $controller->_init(); if (method_exists($controller, $uriinfo['act'])) { call_user_func(array($controller, $uriinfo['act'])); } else { header("HTTP/1.1 404 Not Found"); showError(lang('404_not_found')); } $controller->_called(); } else { header("HTTP/1.1 404 Not Found"); showError(lang('404_not_found')); } } }
/** * Returns parent id * * @param int $cat_id * @return int */ public function getCatParent($h, $cat_id) { //print "getCatParent for id:" . $cat_id . " <br/>****"; if ($h->isTest) { timer_start('getCatParent'); } $category = isset($h->categoriesById[$cat_id]) ? $h->categoriesById[$cat_id] : null; if (!$category) { return false; } if ($h->isTest) { print timer_stop(7, 'getCatParent'); } // timetests averaging 0.0000169, 0.0000198, 0.0000129 - Sep 21, 2014 return $category->category_parent; }
/** * Internal timer stop/start. * * @param string One of 'start' or 'stop'. * @return void */ protected function timer($start_stop) { $this->timer[$start_stop] = microtime(true); if (function_exists('timer_start')) { if ('start' === $start_stop) { timer_start('router'); } else { if ('stop' === $start_stop) { timer_end('router'); } } } }
/** Start timing and get initial memory usage for debug info. **/ function log_start() { $this->start_memory_usage = memory_get_peak_usage(); timer_start(); }
function load_module($module, $sub_module) { // Assuming we fail, ugh! $success = false; // Remember to use $wpdb->prepare or $wpdb->escape when developing module $module = stripslashes($module); $sub_module = stripslashes($sub_module); // Check whether or not splitting is enabled and the sub_module has a 'part' part, // if so, remove it and pass a parameter to let the module knows that it must produce a split sitemap $module_part = 0; $module_virtual = ''; if ('yes' == $this->options['enable_sitemap_split_post'] && preg_match('/part([0-9]+)$/i', $sub_module, $matches)) { $module_virtual = str_replace($matches[0], '', $sub_module); $module_virtual = rtrim($module_virtual, '_'); $module_part = (int) $matches[1]; } $true_sub_module = $sub_module; $pre_module = $module; $pre_module .= !empty($sub_module) ? '_' . $sub_module : ''; // @since 1.0.1 - Redirect to correct domain, with or without www $this->canonical_redirect($pre_module); // Allowed modules $allowed_modules = $this->allowed_modules(); $this->build_requested_modules($allowed_modules); // $this->convert_label($sub_module, $module); if ('sitemapindex' != $module && isset($allowed_modules[$module])) { if (!empty($sub_module)) { if (in_array($sub_module, $allowed_modules[$module]) || empty($module_virtual) && !empty($module_part) && in_array($module, $allowed_modules[$module]) || !empty($module_virtual) && in_array($module_virtual, $allowed_modules[$module])) { $module_key = $module . '_' . $sub_module; } else { $module_key = ''; } } else { $module_key = $module; } $module_name = str_replace($sub_module, $true_sub_module, $module_key); } else { if ('sitemapindex' == $module) { $module_key = 'sitemapindex'; $module_name = 'sitemapindex'; } } // Pass the real sub_module back $sub_module = !empty($module_part) ? $module_virtual : $sub_module; if (empty($module_key)) { $this->elog(sprintf(__('Requested module (<em>%s</em>) not found or not allowed.', 'bwp-simple-gxs'), $pre_module), true, 404); $this->commit_logs(); // If debugging is not enabled, redirect to homepage wp_redirect(home_url()); exit; } // @since 1.0.1 - Start counting correct build time and queries timer_start(); $this->build_stats['query'] = get_num_queries(); // Don't let other instrusive plugins mess up our permalnks - @since 1.1.4 remove_filter('post_link', 'syndication_permalink', 1, 3); remove_filter('page_link', 'suffusion_unlink_page', 10, 2); // If cache is enabled, we check the cache first if ('yes' == $this->options['enable_cache']) { require_once dirname(__FILE__) . '/class-bwp-gxs-cache.php'; $bwp_gxs_cache = new BWP_GXS_CACHE(array('module' => $module_key, 'module_name' => $module_name)); // If cache is ok, output the cached sitemap, only if debug is off if ('yes' != $this->options['enable_debug'] && true == $bwp_gxs_cache->has_cache) { $this->send_header($bwp_gxs_cache->get_header()); $file = $bwp_gxs_cache->get_cache_file(); // Decompress the gz file only if the server or script is not already gzipping, and gzip is enabled // This is to avoid double compression if ('yes' == $this->options['enable_gzip'] && !self::is_gzipped()) { readfile($file); } else { readgzfile($file); } // Get from cache successfully $this->slog(sprintf(__('Successfully served a cached version of <em>%s.xml</em>.', 'bwp-simple-gxs'), $module_name), true); $this->commit_logs(); exit; } } // If the user uses a custom module dir, also check that dir for usable module files $custom_module_dir = !empty($this->options['input_alt_module_dir']) && $this->options_default['input_alt_module_dir'] != $this->options['input_alt_module_dir'] ? trailingslashit($this->options['input_alt_module_dir']) : false; $custom_module_dir = trailingslashit(apply_filters('bwp_gxs_module_dir', $custom_module_dir)); // Begin loading modules require_once dirname(__FILE__) . '/class-bwp-gxs-module.php'; if ('sitemapindex' != $module && isset($allowed_modules[$module])) { $sub_loaded = $mapped_sub_loaded = false; if (!empty($sub_module) && in_array($sub_module, $allowed_modules[$module])) { // Try to load the mapped sub-module first if (!empty($this->module_map[$sub_module])) { $module_file = $module . '_' . $this->module_map[$sub_module] . '.php'; $path_custom = $custom_module_dir ? $this->uni_path_sep($custom_module_dir . $module_file) : ''; $path = $this->uni_path_sep($this->module_directory . $module_file); if (!empty($path_custom) && @file_exists($path_custom)) { $module_key = $module . '_' . $this->module_map[$sub_module]; include_once $path_custom; $mapped_sub_loaded = true; $this->nlog(sprintf(__('Loaded a custom sub-module file: <strong>%s</strong>.', 'bwp-simple-gxs'), $module_file)); } else { if (@file_exists($path)) { $module_key = $module . '_' . $this->module_map[$sub_module]; include_once $path; $mapped_sub_loaded = true; } else { // Don't fire a wp_die $this->nlog(sprintf(__('Mapped sub-module file: <strong>%s</strong> is not available in both default and custom module directory. The plugin will now try loading the requested sub-module instead.', 'bwp-simple-gxs'), $module_file)); } } } if (false == $mapped_sub_loaded) { $module_file = $module . '_' . $sub_module . '.php'; $module_key = $module . '_' . $sub_module; $path_custom = $custom_module_dir ? $this->uni_path_sep($custom_module_dir . $module_file) : ''; $path = $this->uni_path_sep($this->module_directory . $module_file); if (!empty($path_custom) && @file_exists($path_custom)) { include_once $path_custom; $sub_loaded = true; $this->nlog(sprintf(__('Loaded a custom sub-module file: <strong>%s</strong>.', 'bwp-simple-gxs'), $module_file)); } else { if (@file_exists($path)) { include_once $path; $sub_loaded = true; } else { // Don't fire a wp_die $this->nlog(sprintf(__('Sub-module file: <strong>%s</strong> is not available in both default and custom module directory. The plugin will now try loading the parent module instead.', 'bwp-simple-gxs'), $module_file)); } } } } if (false == $sub_loaded && false == $mapped_sub_loaded) { // Try loading the module $module_file = $module . '.php'; $module_key = $module; $path_custom = $custom_module_dir ? $this->uni_path_sep($custom_module_dir . $module_file) : ''; $path = $this->uni_path_sep($this->module_directory . $module_file); if (!empty($path_custom) && @file_exists($path_custom)) { include_once $path_custom; $this->nlog(sprintf(__('Loaded a custom module file: <strong>%s</strong>.', 'bwp-simple-gxs'), $module_file)); } else { if (@file_exists($path)) { include_once $path; } else { $error_log = sprintf(__('Could not load module file: <strong>%s</strong> in both default and custom module directory. Please recheck if that module file exists.', 'bwp-simple-gxs'), $module_file); $this->elog($error_log, true); } } } $this->module_data = array('module' => $module, 'sub_module' => $sub_module, 'module_key' => $module_key, 'module_name' => $module_name, 'module_part' => $module_part); if (class_exists('BWP_GXS_MODULE_' . $module_key)) { $class_name = 'BWP_GXS_MODULE_' . $module_key; $the_module = new $class_name(); if ('url' == $the_module->type) { $success = $this->generate_sitemap($the_module->data); } else { if ('news' == $the_module->type) { $success = $this->generate_news_sitemap($the_module->data); } else { $success = $this->generate_sitemap_index($the_module->data); } } unset($the_module->data); } else { $this->elog(sprintf(__('There is no class named <strong>%s</strong> in the module file <strong>%s</strong>.', 'bwp-simple-gxs'), 'BWP_GXS_MODULE_' . strtoupper($module_key), $module_file), true); } } else { if ('sitemapindex' == $module) { $module_file = 'sitemapindex.php'; $path_custom = $custom_module_dir ? $this->uni_path_sep($custom_module_dir . $module_file) : ''; if (!empty($path_custom) && @file_exists($path_custom)) { include_once $path_custom; $this->nlog(sprintf(__('Loaded a custom sitemapindex module file: <strong>%s</strong>.', 'bwp-simple-gxs'), $module_file)); } else { include_once dirname(__FILE__) . '/modules/sitemapindex.php'; } if (class_exists('BWP_GXS_MODULE_INDEX')) { $the_module = new BWP_GXS_MODULE_INDEX($this->requested_modules); $success = $this->generate_sitemap_index($the_module->data); unset($the_module->data); } } } // Output succeeded if (true == $success) { // Output additional stats if ('yes' == $this->options['enable_stats']) { $this->sitemap_stats(); } // Now cache the sitemap if we have to if ('yes' == $this->options['enable_cache'] && true == $bwp_gxs_cache->cache_ok) { $bwp_gxs_cache->write_cache(); } // Output the requested sitemap $this->output_sitemap(); $this->slog(sprintf(__('Successfully generated <em>%s.xml</em> using module <em>%s</em>.', 'bwp-simple-gxs'), $module_name, $module_file), true); $this->smlog($module_name); $this->commit_logs(); exit; } else { $this->commit_logs(); } }
function wp_mail_receive() { global $wpdb, $wp_pop3, $img_target; require_once ABSPATH . WPINC . '/class-pop3.php'; timer_start(); $use_cache = 1; $time_difference = get_settings('time_difference'); $blog_charset = get_settings('blog_charset'); error_reporting(2037); $wp_pop3 = new POP3(); if (!$wp_pop3->connect(get_settings('mailserver_url'), get_settings('mailserver_port'))) { echo "Ooops {$wp_pop3->ERROR} <br />\n"; return; } $mail_count = $wp_pop3->login(get_settings('mailserver_login'), get_settings('mailserver_pass')); if ($mail_count == false) { if (!$wp_pop3->FP) { echo "Oooops Login Failed: {$wp_pop3->ERROR}<br />\n"; } else { echo "No Message<br />\n"; $wp_pop3->quit(); } return; } // ONLY USE THIS IF YOUR PHP VERSION SUPPORTS IT! register_shutdown_function('wp_mail_quit'); for ($mail_num = 1; $mail_num <= $mail_count; $mail_num++) { $MsgOne = $wp_pop3->get($mail_num); if (!$MsgOne || gettype($MsgOne) != 'array') { echo "oops, {$wp_pop3->ERROR}<br />\n"; $wp_pop3->quit(); return; } $content = ''; $content_type = ''; $boundary = ''; $att_boundary = ''; $hatt_boundary = ''; $bodysignal = 0; $dmonths = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); while (list($lineNum, $line) = each($MsgOne)) { if (strlen($line) < 3) { $bodysignal = 1; } if ($bodysignal) { $content .= $line; } else { if (preg_match('/^Content-Type:\\s+(.*?)\\;/i', $line, $match)) { $content_type = $match[1]; $content_type = strtolower($match[1]); } if ($content_type == 'multipart/mixed' && preg_match('/boundary=(?:")?([^;"\\s\\n]*?)(?:")?\\s*(?:$|;)/', $line, $match) && $att_boundary == '') { $att_boundary = trim($match[1]); } if ($content_type == 'multipart/alternative' && preg_match('/boundary=(?:")?([^;"\\s\\n]*?)(?:")?\\s*(?:$|;)/', $line, $match) && $boundary == '') { $boundary = trim($match[1]); } if ($content_type == 'multipart/related' && preg_match('/boundary=(?:")?([^;"\\s\\n]*?)(?:")?\\s*(?:$|;)/', $line, $match) && $hatt_boundary == '') { $hatt_boundary = trim($match[1]); } if (preg_match('/Subject: /', $line)) { $subject = trim($line); $subject = substr($subject, 9, strlen($subject) - 9); if (function_exists('mb_decode_mimeheader')) { $subject1 = mb_decode_mimeheader($subject); if ($subject != $subject) { $sub_charset = mb_internal_encoding(); } else { $sub_charset = "auto"; } $subject = $subject1; } if (get_settings('use_phoneemail')) { $subject = explode(get_settings('phoneemail_separator'), $subject); $subject = trim($subject[0]); } } if (preg_match('/Date: /', $line)) { // of the form '20 Mar 2002 20:32:37' $ddate = trim($line); $ddate = str_replace('Date: ', '', $ddate); if (strpos($ddate, ',')) { $ddate = trim(substr($ddate, strpos($ddate, ',') + 1, strlen($ddate))); } $ddate_U = strtotime($ddate) + $time_difference * 3600; $post_date = date('Y-m-d H:i:s', $ddate_U); } } } if (!ereg(get_settings('subjectprefix'), $subject)) { continue; } $charset = ""; $ncharset = preg_match("/\\s?charset=\"?([A-Za-z0-9\\-]*)\"?/i", $content, $matches); if ($ncharset) { $charset = $matches[1]; } $ddate_today = time() + $time_difference * 3600; $ddate_difference_days = ($ddate_today - $ddate_U) / 86400; if ($ddate_difference_days > 14) { echo "Too old<br />\n"; continue; } if (preg_match('/' . get_settings('subjectprefix') . '/', $subject)) { $userpassstring = ''; echo "<div style=\"border: 1px dashed #999; padding: 10px; margin: 10px;\">\n"; echo "<p><b>{$mail_num}</b></p><p><b>Subject: </b>{$subject}</p>\n"; $subject = trim(str_replace(get_settings('subjectprefix'), '', $subject)); $attachment = false; if ($att_boundary) { $contents = explode('--' . $att_boundary, $content); $content = $contents[1]; $ncharset = preg_match("/\\s?charset=\"?([A-Za-z0-9\\-]*)\"?/i", $content, $matches); if ($ncharset) { $charset = $matches[1]; } $content = explode("\r\n\r\n", $content, 2); $content = $content[1]; } if ($hatt_boundary) { $contents = explode('--' . $hatt_boundary, $content); $content = $contents[1]; if (preg_match('/Content-Type: multipart\\/alternative\\;\\s*boundary\\=(?:")?([^";\\s\\n]*?)(?:")?\\s*(?:;|\\n|$)"/i', $content, $matches)) { $boundary = trim($matches[1]); $content = explode('--' . $boundary, $content); $content = $content[2]; } $ncharset = preg_match("/charset=\"?([^\"]*)\"?/i", $content, $matches); if ($ncharset) { $charset = $matches[1]; } $content = explode('Content-Transfer-Encoding: quoted-printable', $content); $content = strip_tags($content[1], '<img><p><br><i><b><u><em><strong><strike><font><span><div><dl><dt><dd><ol><ul><li>,<table><tr><td>'); } else { if ($boundary) { $content = explode('--' . $boundary, $content); $content = $content[2]; if (preg_match('/Content-Type: multipart\\/related\\;\\s*boundary=(?:")?([^";\\s\\n]*?)(?:")?\\s*(?:;|\\n|$)/i', $content, $matches)) { $hatt_boundary = trim($matches[1]); $contents = explode('--' . $hatt_boundary, $content); $content = $contents[1]; } $ncharset = preg_match("/charset=\"?([^\"]*)\"?/i", $content, $matches); if ($ncharset) { $charset = $matches[1]; } $content = explode('Content-Transfer-Encoding: quoted-printable', $content); $content = strip_tags($content[1], '<img><p><br><i><b><u><em><strong><strike><font><span><div><dl><dt><dd><ol><ul><li>,<table><tr><td>'); } } $content = trim($content); echo "<p><b>Content-type:</b> {$content_type}, <b>boundary:</b> {$boundary}</p>\n"; echo "<p><b>att_boundary:</b> {$att_boundary}, <b>hatt_boundary:</b> {$hatt_boundary}</p>\n"; echo "<p><b>charset:</b>{$charset}, <b>BLOG charset:</b>{$blog_charset}</p>\n"; // echo "<p><b>Raw content:</b><br /><pre>".$content.'</pre></p>'; if ($charset == "" || trim(strtoupper($charset)) == "ISO-2022-JP") { $charset = "JIS"; } if (trim(strtoupper($charset)) == "SHIFT_JIS") { $charset = "SJIS"; } $btpos = strpos($content, get_settings('bodyterminator')); if ($btpos) { $content = substr($content, 0, $btpos); } $content = trim($content); $blah = explode("\n", preg_replace("/^[\n\r\\s]*/", "", strip_tags($content))); $firstline = preg_replace("/[\n\r]/", "", $blah[0]); $secondline = $blah[1]; if (get_settings('use_phoneemail')) { echo "<p><b>Use Phone Mail:</b> Yes</p>\n"; $btpos = strpos($firstline, get_settings('phoneemail_separator')); if ($btpos) { $userpassstring = trim(substr($firstline, 0, $btpos)); $content = trim(substr($content, $btpos + strlen(get_settings('phoneemail_separator')), strlen($content))); $btpos = strpos($content, get_settings('phoneemail_separator')); if ($btpos) { $userpassstring = trim(substr($content, 0, $btpos)); $content = trim(substr($content, $btpos + strlen(get_settings('phoneemail_separator')), strlen($content))); } } $contentfirstline = $blah[1]; } else { echo "<p><b>Use Phone Mail:</b> No</p>\n"; $userpassstring = strip_tags($firstline); $contentfirstline = ''; } $flat = 999.0; $flon = 999.0; $secondlineParts = explode(':', strip_tags($secondline)); if (strncmp($secondlineParts[0], "POS", 3) == 0) { echo "Found POS:<br />\n"; // echo "Second parts is:".$secondlineParts[1]; // the second line is the postion listing line $secLineParts = explode(',', $secondlineParts[1]); $flatStr = $secLineParts[0]; $flonStr = $secLineParts[1]; // echo "String are ".$flatStr.$flonStr; $flat = floatval($secLineParts[0]); $flon = floatval($secLineParts[1]); // echo "values are ".$flat." and ".$flon; // ok remove that position... we should not have it in the final output $content = str_replace($secondline, '', $content); } $blah = explode(':', $userpassstring); $user_login = $blah[0]; $user_pass = $blah[1]; $user_login = mb_conv(trim($user_login), $blog_charset, $charset); $content = $contentfirstline . str_replace($firstline, '', $content); $content = trim($content); // Please uncomment following line, only if you want to check user and password. // echo "<p><b>Login:</b> $user_login, <b>Pass:</b> $user_pass</p>"; echo "<p><b>Login:</b> {$user_login}, <b>Pass:</b> *********</p>"; if (!user_pass_ok($user_login, $user_pass)) { echo "<p><b>Error: Wrong Login.</b></p></div>\n"; continue; } $userdata = get_userdatabylogin($user_login); $user_level = $userdata->user_level; $post_author = $userdata->ID; if ($user_level > 0) { $post_title = xmlrpc_getposttitle($content); if ($post_title == '') { $post_title = $subject; } echo "Subject : " . mb_conv($post_title, $blog_charset, $sub_charset) . " <br />\n"; $post_category = get_settings('default_category'); if (preg_match('/<category>(.+?)<\\/category>/is', $content, $matchcat)) { $post_category = xmlrpc_getpostcategory($content); } if (empty($post_category)) { $post_category = get_settings('default_post_category'); } echo "Category : {$post_category} <br />\n"; $post_category = explode(',', $post_category); if (!get_settings('emailtestonly')) { // Attaching Image Files Save if ($att_boundary != "") { $attachment = wp_getattach($contents[2], "user-" . trim($post_author), 1); } if ($boundary != "" && $hatt_boundary != "") { for ($i = 2; $i < count($contents); $i++) { $hattachment = wp_getattach($contents[$i], "user-" . trim($post_author), 0); if ($hattachment) { if (preg_match("/Content-Id: \\<([^\\>]*)>/i", $contents[$i], $matches)) { $content = preg_replace("/(cid:" . preg_quote($matches[1]) . ")/", get_settings('fileupload_url') . '/' . $hattachment, $content); } } } } if ($boundary != "") { $content = preg_replace("/\\=[\r\n]/", "", $content); $content = preg_replace("/[\r\n]/", " ", $content); } $content = preg_replace("|\n([^\n])|", " \$1", $content); $content = preg_replace("/\\=([0-9a-fA-F]{2,2})/e", "pack('c',base_convert('\\1',16,10))", $content); $content = mb_conv(trim($content), $blog_charset, $charset); // If we find an attachment, add it to the post if ($attachment) { if (isset($img_target) && $img_target) { $img_target = ' target="' . $img_target . '"'; } else { $img_target = ''; } if (file_exists(get_settings('fileupload_realpath') . "/thumb-" . $attachment)) { $content = "<a href=\"" . get_settings('fileupload_url') . '/' . rawurlencode($attachment) . "\"" . $img_target . "><img style=\"float: left;\" hspace=\"6\" src = \"" . get_settings('fileupload_url') . '/thumb-' . rawurlencode($attachment) . "\" alt=\"" . $attachment . "\" title=\"" . $attachment . "\" /></a>" . $content . "<br clear=\"left\" />"; } else { $content = "<a href=\"" . get_settings('fileupload_url') . '/' . rawurlencode($attachment) . "\"" . $img_target . "><img style=\"float: left;\" hspace=\"6\" src = \"" . get_settings('fileupload_url') . '/' . rawurlencode($attachment) . "\" alt=\"" . $attachment . "\" title=\"" . $attachment . "\" /></a>" . $content . "<br clear=\"left\" />"; } } $postHandler =& wp_handler('Post'); $postObject =& $postHandler->create(); $postObject->setVar('post_content', $content); $postObject->setVar('post_title', trim(mb_conv($post_title, $blog_charset, $sub_charset))); $postObject->setVar('post_date', $post_date); $postObject->setVar('post_author', $post_author); $postObject->setVar('post_category', $post_category[0]); $postObject->setVar('post_name', sanitize_title($post_title)); if ($flat < 500) { $postObject->setVar('post_lat', $flat); $postObject->setVar('post_lon', $flon); } if (!$postHandler->insert($postObject, true)) { echo "<b>Error: Insert New Post</b><br />"; } $post_ID = $postObject->getVar('ID'); echo "Post ID = {$post_ID}<br />\n"; $postObject->assignCategories($post_category); do_action('publish_post', $post_ID); do_action('publish_phone', $post_ID); if ($flat < 500) { pingGeoUrl($post_ID); } $blog_ID = 1; pingWeblogs($blog_ID); pingBlogs($blog_ID); pingback($content, $post_ID); } echo "\n<p><b>Posted title:</b> {$post_title}<br />\n"; echo "<b>Posted content:</b><br /><pre>" . $content . "</pre></p>\n"; if (!$wp_pop3->delete($mail_num)) { echo "<p>Oops " . $wp_pop3->ERROR . "</p></div>\n"; $wp_pop3->reset(); return; } else { echo "<p>Mission complete, message <strong>{$mail_num}</strong> deleted.</p>\n"; } } else { echo "<p><strong>Level 0 users can\\'t post.</strong></p>\n"; } echo "</div>\n"; } } $wp_pop3->quit(); timer_stop($output_debugging_info); return; }
/** * Get Account Status * NOTE: You shouldnt need to call this directly. Its called in the constructor. * Request: https://LINGOTEK_BILLING_SERVER/billing/account.json?community=B2MMD3X5&external_id=community_admin&oauth_key=28c279fa-28dc-452e-93af-68d194a2c366&oauth_secret=0e999486-3b4d-47e4-ba9a-d0f3f0bbda73 * Response: {"state":"active","plan":{"trial_ends_at":0,"state":"active","activated_at":1355267936,"type":"cosmopolitan_monthly","languages_allowed":2,"language_cost_per_period_in_cents":14900}} * Will return FALSE or a json decoded object. */ function getAccountStatus() { $result = FALSE; $parameters = array('community' => variable_get('lingotek_community_identifier', ''), 'external_id' => variable_get('lingotek_login_id', ''), 'oauth_key' => variable_get('lingotek_oauth_consumer_id', ''), 'oauth_secret' => variable_get('lingotek_oauth_consumer_secret', '')); if (!empty($parameters['community']) && !empty($parameters['external_id']) && !empty($parameters['oauth_key']) && !empty($parameters['oauth_secret'])) { $timer_name = 'GET -' . microtime(TRUE); timer_start($timer_name); $api_url = LINGOTEK_BILLING_SERVER; $ch = curl_init($api_url . '?' . http_build_query($parameters)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //curl_setopt( $ch, CURLINFO_HEADER_OUT, TRUE ); $response = curl_exec($ch); $info = curl_getinfo($ch); curl_close($ch); $response_json = json_decode($response); //debug( $response ); //debug( $info ); $timer_results = timer_stop($timer_name); $message_params = array('@url' => $api_url, '@method' => 'GET account (billing API)', '!params' => $parameters, '!response' => $response_json, '@response_time' => number_format($timer_results['time']) . ' ms'); if (isset($response_json) && $info['http_code'] == 200) { // Did we get valid json data back? If not, $json is NULL. //debug ( $json ); LingotekLog::info('<h1>@method</h1> <strong>API URL:</strong> @url <br /><strong>Response Time:</strong> @response_time<br /><strong>Request Params</strong>: !params<br /><strong>Response:</strong> !response', $message_params, 'api'); $response_data = $response; $result = TRUE; // Not Found - {"state":"not_found"} - Account isn't setup yet. The state after autoprovisioning a community, but before setting up your billing account. if ($response_json->state == self::NOT_FOUND) { $this->setStatus(self::NOT_FOUND); $this->setPlan(self::NONE); } elseif ($response_json->state == self::ACTIVE) { $this->setStatus(self::ACTIVE); variable_set('lingotek_account_status', self::ACTIVE); if (is_object($response_json->plan)) { $this->setPlan($response_json->plan); } // END: Plan menu_rebuild(); } // END Active } else { LingotekLog::error('<h1>@method (Failed)</h1> <strong>API URL:</strong> @url <br /><strong>Response Time:</strong> @response_time<br /><strong>Request Params</strong>: !params<br /><strong>Response:</strong> !response<br/><strong>Full Request:</strong> !request', $message_params, 'api'); } } // END: has credentials return $result; }
function filedepot_dispatcher($action) { global $user; $filedepot = filedepot_filedepot(); $nexcloud = filedepot_nexcloud(); module_load_include('php', 'filedepot', 'lib-theme'); module_load_include('php', 'filedepot', 'lib-ajaxserver'); module_load_include('php', 'filedepot', 'lib-common'); if (function_exists('timer_start')) { timer_start('filedepot_timer'); } firelogmsg("AJAX Server code executing - action: {$action}"); switch ($action) { case 'archive': if (isset($_GET['checked_files']) && isset($_GET['checked_folders'])) { module_load_include('php', 'filedepot', 'filedepot_archiver.class'); $checked_files = json_decode($_GET['checked_files'], TRUE); $checked_folders = json_decode($_GET['checked_folders'], TRUE); //print_r($checked_files); //die(1); $fa = new filedepot_archiver(); $fa->createAndCleanArchiveDirectory(); $fa->addCheckedObjectArrays($checked_files, $checked_folders); $fa->createArchive(); $fa->close(); $fa->download(); return; } else { echo "Invalid Parameters"; return; } break; case 'getfilelisting': $cid = intval($_POST['cid']); if ($cid > 0) { if (db_query("SELECT count(*) FROM {filedepot_categories} WHERE cid=:cid", array(':cid' => $cid))->fetchField() == 1) { $filedepot->ajaxBackgroundMode = TRUE; } } $reportmode = check_plain($_POST['reportmode']); $filedepot->activeview = $reportmode; $filedepot->cid = $cid; ctools_include('object-cache'); $cache = ctools_object_cache_set('filedepot', 'folder', $cid); $data = filedepotAjaxServer_getfilelisting(); break; case 'getfolderlisting': $filedepot->ajaxBackgroundMode = TRUE; $cid = intval($_POST['cid']); $reportmode = check_plain($_POST['reportmode']); if ($cid > 0) { ctools_include('object-cache'); $cache = ctools_object_cache_set('filedepot', 'folder', $cid); $filedepot->cid = $cid; $filedepot->activeview = $reportmode; $data = filedepotAjaxServer_getfilelisting(); firelogmsg("Completed generating FileListing"); } else { $data = array('retcode' => 500); } break; case 'getleftnavigation': $data = filedepotAjaxServer_generateLeftSideNavigation(); break; case 'getmorefiledata': /** Need to use XML instead of JSON format for return data. * It's taking up to 1500ms to interpret (eval) the JSON data into an object in the client code * Parsing the XML is about 10ms */ $cid = intval($_POST['cid']); $level = intval($_POST['level']); $foldernumber = check_plain($_POST['foldernumber']); $filedepot->activeview = 'getmoredata'; $filedepot->cid = $cid; $filedepot->lastRenderedFolder = $cid; $retval = '<result>'; $retval .= '<retcode>200</retcode>'; $retval .= '<displayhtml>' . htmlspecialchars(nexdocsrv_generateFileListing($cid, $level, $foldernumber), ENT_QUOTES, 'utf-8') . '</displayhtml>'; $retval .= '</result>'; firelogmsg("Completed generating AJAX return data - cid: {$cid}"); break; case 'getmorefolderdata': /* Need to use XML instead of JSON format for return data. It's taking up to 1500ms to interpret (eval) the JSON data into an object in the client code Parsing the XML is about 10ms */ $cid = intval($_POST['cid']); $level = intval($_POST['level']); // Need to remove the last part of the passed in foldernumber as it's the incremental file number // Which we recalculate in template_preprocess_filelisting() $x = explode('.', check_plain($_POST['foldernumber'])); $x2 = array_pop($x); $foldernumber = implode('.', $x); $filedepot->activeview = 'getmorefolderdata'; $filedepot->cid = $cid; $filedepot->lastRenderedFolder = $cid; $retval = '<result>'; $retval .= '<retcode>200</retcode>'; $retval .= '<displayhtml>' . htmlspecialchars(nexdocsrv_generateFileListing($cid, $level, $foldernumber), ENT_QUOTES, 'utf-8') . '</displayhtml>'; $retval .= '</result>'; firelogmsg("Completed generating AJAX return data - cid: {$cid}"); break; case 'rendernewfilefolderoptions': $cid = intval($_POST['cid']); $data['displayhtml'] = theme('filedepot_newfiledialog_folderoptions', array('cid' => $cid)); break; case 'rendernewfolderform': $cid = intval($_POST['cid']); $data['displayhtml'] = theme('filedepot_newfolderdialog', array('cid' => $cid)); break; case 'createfolder': $node = (object) array('uid' => $user->uid, 'name' => $user->name, 'type' => 'filedepot_folder', 'title' => $_POST['catname'], 'parentfolder' => intval($_POST['catparent']), 'folderdesc' => $_POST['catdesc'], 'inherit' => intval($_POST['catinherit'])); if ($node->parentfolder == 0 and !user_access('administer filedepot')) { $data['errmsg'] = t('Error creating Folder - invalid parent folder'); $data['retcode'] = 500; } else { node_save($node); if ($node->nid) { $data['displaycid'] = $filedepot->cid; $data['retcode'] = 200; } else { $data['errmsg'] = t('Error creating Folder'); $data['retcode'] = 500; } } break; case 'deletefolder': $data = array(); $cid = intval($_POST['cid']); $token = isset($_POST['token']) ? $_POST['token'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FOLDERMGMT)) { $data['retcode'] = 403; // Forbidden } else { $query = db_query("SELECT cid,pid,nid FROM {filedepot_categories} WHERE cid=:cid", array(':cid' => $cid)); $A = $query->fetchAssoc(); if ($cid > 0 and $A['cid'] = $cid) { if ($filedepot->checkPermission($cid, 'admin')) { node_delete($A['nid']); $filedepot->cid = $A['pid']; // Set the new active directory to the parent folder $data['retcode'] = 200; $data['activefolder'] = theme('filedepot_activefolder'); $data['displayhtml'] = filedepot_displayFolderListing($filedepot->cid); $data = filedepotAjaxServer_generateLeftSideNavigation($data); } else { $data['retcode'] = 403; // Forbidden } } else { $data['retcode'] = 404; // Not Found } } break; case 'updatefolder': $token = isset($_POST['token']) ? $_POST['token'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FOLDERMGMT)) { $data['retcode'] = 403; // Forbidden } else { $data = filedepotAjaxServer_updateFolder(); } break; case 'setfolderorder': $cid = intval($_POST['cid']); $filedepot->cid = intval($_POST['listingcid']); $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) { $data['retcode'] = 403; // Forbidden } else { if ($filedepot->checkPermission($cid, 'admin')) { // Check and see if any subfolders don't yet have a order value - if so correct $maxorder = 0; $pid = db_query("SELECT pid FROM {filedepot_categories} WHERE cid=:cid", array(':cid' => $cid))->fetchField(); $maxquery = db_query_range("SELECT folderorder FROM {filedepot_categories} WHERE pid=:pid ORDER BY folderorder ASC", 0, 1, array(':pid' => $pid))->fetchField(); $next_folderorder = $maxorder + 10; $query = db_query("SELECT cid FROM {filedepot_categories} WHERE pid=:pid AND folderorder = 0", array(':pid' => $pid)); while ($B = $query->fetchAssoc()) { db_query("UPDATE {filedepot_categories} SET folderorder=:folderorder WHERE cid=:cid", array(':folderorder' => $next_folderorder, ':cid' => $B['cid'])); $next_folderorder += 10; } $itemquery = db_query("SELECT * FROM {filedepot_categories} WHERE cid=:cid", array(':cid' => $cid)); $retval = 0; while ($A = $itemquery->fetchAssoc()) { if ($_POST['direction'] == 'down') { $sql = "SELECT folderorder FROM {filedepot_categories} WHERE pid=:pid "; $sql .= "AND folderorder > :folderorder ORDER BY folderorder ASC "; $nextorder = db_query_range($sql, 0, 1, array(':pid' => $A['pid'], ':folderorder' => $A['folderorder']))->fetchField(); if ($nextorder > $A['folderorder']) { $folderorder = $nextorder + 5; } else { $folderorder = $A['folderorder']; } db_query("UPDATE {filedepot_categories} SET folderorder=:folderorder WHERE cid=:cid", array(':folderorder' => $folderorder, ':cid' => $cid)); } elseif ($_POST['direction'] == 'up') { $sql = "SELECT folderorder FROM {filedepot_categories} WHERE pid=:pid "; $sql .= "AND folderorder < :folderorder ORDER BY folderorder DESC "; $nextorder = db_query_range($sql, 0, 1, array(':pid' => $A['pid'], ':folderorder' => $A['folderorder']))->fetchField(); $folderorder = $nextorder - 5; if ($folderorder <= 0) { $folderorder = 0; } db_query("UPDATE {filedepot_categories} SET folderorder=:folderorder WHERE cid=:cid", array(':folderorder' => $folderorder, ':cid' => $cid)); } } /* Re-order any folders that may have just been moved */ $query = db_query("SELECT cid,folderorder from {filedepot_categories} WHERE pid=:pid ORDER BY folderorder", array(':pid' => $pid)); $folderorder = 10; $stepnumber = 10; while ($A = $query->fetchAssoc()) { if ($folderorder != $A['folderOrder']) { db_query("UPDATE {filedepot_categories} SET folderorder=:folderorder WHERE cid=:cid", array(':folderorder' => $folderorder, ':cid' => $A['cid'])); } $folderorder += $stepnumber; } $data['retcode'] = 200; $data['displayhtml'] = filedepot_displayFolderListing($filedepot->cid); } else { $data['retcode'] = 400; } } break; case 'updatefoldersettings': $cid = intval($_POST['cid']); $notifyadd = intval($_POST['fileadded_notify']); $notifychange = intval($_POST['filechanged_notify']); if ($user->uid > 0 and $cid >= 1) { // Update the personal folder notifications for user if (db_query("SELECT count(*) FROM {filedepot_notifications} WHERE cid=:cid AND uid=:uid", array(':cid' => $cid, ':uid' => $user->uid))->fetchField() == 0) { $sql = "INSERT INTO {filedepot_notifications} (cid,cid_newfiles,cid_changes,uid,date) "; $sql .= "VALUES (:cid,:notifyadd,:notifychange,:uid,:time)"; db_query($sql, array(':cid' => $cid, ':notifyadd' => $notifyadd, ':notifychange' => $notifychange, ':uid' => $user->uid, ':time' => time())); } else { $sql = "UPDATE {filedepot_notifications} set cid_newfiles=:notifyadd, "; $sql .= "cid_changes=:notifychange, date=:time "; $sql .= "WHERE uid=:uid and cid=:cid"; db_query($sql, array(':notifyadd' => $notifyadd, ':notifychange' => $notifychange, ':time' => time(), ':uid' => $user->uid, ':cid' => $cid)); } $data['retcode'] = 200; $data['displayhtml'] = filedepot_displayFolderListing($filedepot->cid); } else { $data['retcode'] = 500; } break; case 'loadfiledetails': $data = filedepotAjaxServer_loadFileDetails(); break; case 'refreshfiledetails': $reportmode = check_plain($_POST['reportmode']); $fid = intval($_POST['id']); $cid = db_query("SELECT cid FROM {filedepot_files} WHERE fid=:fid", array(':fid' => $fid))->fetchField(); if ($filedepot->checkPermission($cid, 'view')) { $data['retcode'] = 200; $data['fid'] = $fid; $data['displayhtml'] = theme('filedepot_filedetail', array('fid' => $fid, 'reportmode' => $reportmode)); } else { $data['retcode'] = 400; $data['error'] = t('Invalid access'); } break; case 'updatenote': $fid = intval($_POST['fid']); $version = intval($_POST['version']); $note = check_plain($_POST['note']); $reportmode = check_plain($_POST['reportmode']); $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) { $data['retcode'] = 403; // forbidden } elseif ($fid > 0) { db_query("UPDATE {filedepot_fileversions} SET notes=:notes WHERE fid=:fid and version=:version", array(':notes' => $note, ':fid' => $fid, ':version' => $version)); $data['retcode'] = 200; $data['fid'] = $fid; $data['displayhtml'] = theme('filedepot_filedetail', array('fid' => $fid, 'reportmode' => $reportmode)); } else { $data['retcode'] = 400; } break; case 'getfolderperms': $cid = intval($_POST['cid']); if ($cid > 0) { if ($filedepot->ogenabled) { $data['html'] = theme('filedepot_folderperms_ogenabled', array('cid' => $cid, 'token' => drupal_get_token(FILEDEPOT_TOKEN_FOLDERPERMS))); } else { $data['html'] = theme('filedepot_folderperms', array('cid' => $cid, 'token' => drupal_get_token(FILEDEPOT_TOKEN_FOLDERPERMS))); } $data['retcode'] = 200; } else { $data['retcode'] = 404; } break; case 'delfolderperms': $id = intval($_POST['id']); $token = isset($_POST['token']) ? $_POST['token'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FOLDERPERMS)) { $data['retcode'] = 403; // forbidden } elseif ($id > 0) { $query = db_query("SELECT catid, permtype, permid FROM {filedepot_access} WHERE accid=:accid", array(':accid' => $id)); $A = $query->fetchAssoc(); if ($filedepot->checkPermission($A['catid'], 'admin')) { db_delete('filedepot_access')->condition('accid', $id)->execute(); db_update('filedepot_usersettings')->fields(array('allowable_view_folders' => ''))->execute(); // For this folder - I need to update the access metrics now that a permission has been removed $nexcloud->update_accessmetrics($A['catid']); if ($filedepot->ogenabled) { $data['html'] = theme('filedepot_folderperms_ogenabled', array('cid' => $A['catid'], 'token' => drupal_get_token(FILEDEPOT_TOKEN_FOLDERPERMS))); } else { $data['html'] = theme('filedepot_folderperms', array('cid' => $A['catid'], 'token' => drupal_get_token(FILEDEPOT_TOKEN_FOLDERPERMS))); } $data['retcode'] = 200; } else { $data['retcode'] = 403; // Forbidden } } else { $data['retcode'] = 404; // Not Found } break; case 'addfolderperm': $cid = intval($_POST['catid']); $token = isset($_POST['token']) ? $_POST['token'] : NULL; if (!isset($_POST['cb_access'])) { $data['retcode'] = 204; // No permission options selected - return 'No content' statuscode } elseif ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FOLDERPERMS)) { $data['retcode'] = 403; // forbidden } elseif ($filedepot->updatePerms($cid, $_POST['cb_access'], $_POST['selusers'], $_POST['selgroups'], $_POST['selroles'])) { if (is_array($_POST['selroles']) and count($_POST['selroles']) > 0) { foreach ($_POST['selroles'] as $roleid) { $roleid = intval($roleid); if ($roleid > 0) { $nexcloud->update_accessmetrics($cid); } } } if ($filedepot->ogenabled) { if (is_array($_POST['selgroups']) and count($_POST['selgroups']) > 0) { foreach ($_POST['selgroups'] as $groupid) { $groupid = intval($groupid); if ($groupid > 0) { $nexcloud->update_accessmetrics($cid); } } } $data['html'] = theme('filedepot_folderperms_ogenabled', array('cid' => $cid, 'token' => drupal_get_token(FILEDEPOT_TOKEN_FOLDERPERMS))); } else { $data['html'] = theme('filedepot_folderperms', array('cid' => $cid, 'token' => drupal_get_token(FILEDEPOT_TOKEN_FOLDERPERMS))); } $data['retcode'] = 200; } else { $data['retcode'] = 403; // Forbidden } break; case 'updatefile': $fid = intval($_POST['id']); $folder_id = intval($_POST['folder']); $version = intval($_POST['version']); $filetitle = $_POST['filetitle']; $description = $_POST['description']; $vernote = $_POST['version_note']; $approved = check_plain($_POST['approved']); $tags = $_POST['tags']; $data = array(); $data['tagerror'] = ''; $data['errmsg'] = ''; $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) { $data['retcode'] = 403; // forbidden $data['errmsg'] = t('Invalid request'); } elseif ($_POST['cid'] == 'incoming' and $fid > 0) { $filemoved = FALSE; $sql = "UPDATE {filedepot_import_queue} SET orig_filename=:filename, description=:description,"; $sql .= "version_note=:notes WHERE id=:fid"; db_query($sql, array(':filename' => $filetitle, ':description' => $description, ':notes' => $vernote, ':fid' => $fid)); $data['retcode'] = 200; if ($folder_id > 0 and $filedepot->moveIncomingFile($fid, $folder_id)) { $filemoved = TRUE; $filedepot->activeview = 'incoming'; $data = filedepotAjaxServer_generateLeftSideNavigation($data); $data['displayhtml'] = filedepot_displayFolderListing(); } } elseif ($fid > 0) { $filemoved = FALSE; if ($approved == 0) { $sql = "UPDATE {filedepot_filesubmissions} SET title=:title, description=:description,"; $sql .= "version_note=:notes, cid=:cid, tags=:tags WHERE id=:fid;"; db_query($sql, array(':title' => $filetitle, ':description' => $description, ':notes' => $vernote, ':cid' => $folder_id, ':tags' => $tags, ':fid' => $fid)); $data['cid'] = $folder_id; $data['tags'] = ''; } else { $query = db_query("SELECT fname,cid,version,submitter FROM {filedepot_files} WHERE fid=:fid", array(':fid' => $fid)); list($fname, $cid, $current_version, $submitter) = array_values($query->fetchAssoc()); // Allow updating the category, title, description and image for the current version and primary file record if ($version == $current_version) { db_query("UPDATE {filedepot_files} SET title=:title,description=:desc,date=:time WHERE fid=:fid", array(':title' => $filetitle, ':desc' => $description, ':time' => time(), ':fid' => $fid)); // Test if user has selected a different directory and if they have perms then move else return FALSE; if ($folder_id > 0) { $newcid = $folder_id; if ($cid != $newcid) { $filemoved = $filedepot->moveFile($fid, $newcid); if ($filemoved == FALSE) { $data['errmsg'] = t('Error moving file'); } } $data['cid'] = $newcid; } else { $data['cid'] = $cid; } unset($_POST['tags']); // Format tags will check this to format tags in case we are doing a search which we are not in this case. $data['tags'] = filedepot_formatfiletags($tags); } db_query("UPDATE {filedepot_fileversions} SET notes=:notes WHERE fid=:fid and version=:version", array(':notes' => $vernote, ':fid' => $fid, ':version' => $version)); // Update the file tags if role or group permission set -- we don't support tag access perms at the user level. if ($filedepot->checkPermission($folder_id, 'view', 0, FALSE)) { if ($filedepot->checkPermission($folder_id, 'admin', 0, FALSE) or $user->uid == $submitter) { $admin = TRUE; } else { $admin = FALSE; } if (!$nexcloud->update_tags($fid, $tags, $admin)) { $data['tagerror'] = t('Tags not added - Group or Role assigned view perms required'); $data['tags'] = ''; } } else { $data['tagerror'] = t('Problem adding or updating tags'); $data['tags'] = ''; } } $data['retcode'] = 200; $data['tagcloud'] = theme('filedepot_tagcloud'); } else { $data['retcode'] = 500; $data['errmsg'] = t('Invalid File'); } $data['description'] = nl2br(filter_xss($description)); $data['fid'] = $fid; $data['filename'] = filter_xss($filetitle); $data['filemoved'] = $filemoved; break; case 'deletefile': $fid = intval($_POST['fid']); $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) { $data['retcode'] = 403; // forbidden } elseif ($user->uid > 0 and $fid > 0) { $data = filedepotAjaxServer_deleteFile($fid); } else { $data['retcode'] = 500; } break; case 'deletecheckedfiles': $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) { $data['retcode'] = 403; // forbidden } elseif ($user->uid > 0) { $data = filedepotAjaxServer_deleteCheckedFiles(); } else { $data['retcode'] = 500; } break; case 'deleteversion': $fid = intval($_POST['fid']); $version = intval($_POST['version']); $reportmode = check_plain($_POST['reportmode']); $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) { $data['retcode'] = 403; // forbidden } elseif ($fid > 0 and $version > 0) { if ($filedepot->deleteVersion($fid, $version)) { $data['retcode'] = 200; $data['fid'] = $fid; $data['displayhtml'] = theme('filedepot_filedetail', array('fid' => $fid, 'reportmode' => $reportmode)); } else { $data['retcode'] = 400; } } else { $data['retcode'] = 400; } break; case 'togglefavorite': $id = intval($_POST['id']); $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) { $data['retcode'] = 403; // forbidden } elseif ($user->uid > 0 and $id >= 1) { if (db_query("SELECT count(fid) FROM {filedepot_favorites} WHERE uid=:uid AND fid=:fid", array(':uid' => $user->uid, ':fid' => $id))->fetchField() > 0) { $data['favimgsrc'] = base_path() . drupal_get_path('module', 'filedepot') . '/css/images/' . $filedepot->getFileIcon('favorite-off'); db_query("DELETE FROM {filedepot_favorites} WHERE uid=:uid AND fid=:fid", array(':uid' => $user->uid, ':fid' => $id)); } else { $data['favimgsrc'] = base_path() . drupal_get_path('module', 'filedepot') . '/css/images/' . $filedepot->getFileIcon('favorite-on'); db_query("INSERT INTO {filedepot_favorites} (uid,fid) VALUES (:uid,:fid)", array(':uid' => $user->uid, ':fid' => $id)); } $data['retcode'] = 200; } else { $data['retcode'] = 400; } break; case 'markfavorite': $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) { $data['retcode'] = 403; // forbidden } elseif ($user->uid > 0) { $cid = intval($_POST['cid']); $reportmode = check_plain($_POST['reportmode']); $fileitems = check_plain($_POST['checkeditems']); $files = explode(',', $fileitems); $filedepot->cid = $cid; $filedepot->activeview = $reportmode; foreach ($files as $id) { if ($id > 0 and db_query("SELECT COUNT(*) FROM {filedepot_favorites} WHERE uid=:uid AND fid=:fid", array(':uid' => $user->uid, ':fid' => $id))->fetchField() == 0) { db_query("INSERT INTO {filedepot_favorites} (uid,fid) VALUES (:uid,:fid)", array(':uid' => $user->uid, 'fid' => $id)); } } $data['retcode'] = 200; $data['displayhtml'] = filedepot_displayFolderListing($cid); } break; case 'clearfavorite': $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) { $data['retcode'] = 403; // forbidden } elseif ($user->uid > 0) { $cid = intval($_POST['cid']); $reportmode = check_plain($_POST['reportmode']); $fileitems = check_plain($_POST['checkeditems']); $files = explode(',', $fileitems); $filedepot->cid = $cid; $filedepot->activeview = $reportmode; foreach ($files as $id) { if ($id > 0 and db_query("SELECT COUNT(*) FROM {filedepot_favorites} WHERE uid=:uid AND fid=:fid", array(':uid' => $user->uid, ':fid' => $id))->fetchField() == 1) { db_query("DELETE FROM {filedepot_favorites} WHERE uid=:uid AND fid=:fid", array(':uid' => $user->uid, ':fid' => $id)); } } $data['retcode'] = 200; $data['displayhtml'] = filedepot_displayFolderListing($cid); } break; case 'togglelock': $fid = intval($_POST['fid']); $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) { $data['error'] = t('Error locking file'); } else { $data['error'] = ''; $data['fid'] = $fid; $query = db_query("SELECT status FROM {filedepot_files} WHERE fid=:fid", array(':fid' => $fid)); if ($query) { list($status) = array_values($query->fetchAssoc()); if ($status == 1) { db_query("UPDATE {filedepot_files} SET status='2', status_changedby_uid=:uid WHERE fid=:fid", array(':uid' => $user->uid, ':fid' => $fid)); $stat_user = db_query("SELECT name FROM {users} WHERE uid=:uid", array(':uid' => $user->uid))->fetchField(); $data['message'] = 'File Locked successfully'; $data['locked_message'] = '* ' . t('Locked by %name', array('%name' => $stat_user)); $data['locked'] = TRUE; } else { db_query("UPDATE {filedepot_files} SET status='1', status_changedby_uid=:uid WHERE fid=:fid", array(':uid' => $user->uid, ':fid' => $fid)); $data['message'] = 'File Un-Locked successfully'; $data['locked'] = FALSE; } } else { $data['error'] = t('Error locking file'); } } break; case 'movecheckedfiles': $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) { $data['retcode'] = 403; // forbidden } elseif ($user->uid > 0) { $data = filedepotAjaxServer_moveCheckedFiles(); } else { $data['retcode'] = 500; } break; case 'rendermoveform': $data['displayhtml'] = theme('filedepot_movefiles_form'); break; case 'rendermoveincoming': $data['displayhtml'] = theme('filedepot_moveincoming_form'); break; case 'togglesubscribe': $fid = intval($_POST['fid']); $cid = intval($_POST['cid']); $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) { $data['error'] = t('Error subscribing'); } else { global $base_url; $data['error'] = ''; $data['fid'] = $fid; $ret = filedepotAjaxServer_updateFileSubscription($fid, 'toggle'); // @TODO: Notifyicon does not appear to be implemented if ($ret['retcode'] === TRUE) { $data['retcode'] = 200; if ($ret['subscribed'] === TRUE) { $data['subscribed'] = TRUE; $data['message'] = 'You will be notified of any new versions of this file'; $path = drupal_get_path('module', 'filedepot') . '/css/images/email-green.gif'; $data['notifyicon'] = $base_url . '/' . $path; $data['notifymsg'] = 'Notification Enabled - Click to change'; } elseif ($ret['subscribed'] === FALSE) { $data['subscribed'] = FALSE; $data['message'] = 'You will not be notified of any new versions of this file'; $path = drupal_get_path('module', 'filedepot') . '/css/images/email-regular.gif'; $data['notifyicon'] = $base_url . '/' . $path; $data['notifymsg'] = 'Notification Disabled - Click to change'; } } else { $data['error'] = t('Error accessing file record'); $data['retcode'] = 404; } } break; case 'updatenotificationsettings': if ($user->uid > 0) { if (db_query("SELECT count(uid) FROM {filedepot_usersettings} WHERE uid=:uid", array(':uid' => $user->uid))->fetchField() == 0) { db_query("INSERT INTO {filedepot_usersettings} (uid) VALUES ( :uid )", array(':uid' => $user->uid)); } $sql = "UPDATE {filedepot_usersettings} SET notify_newfile=:newfile,notify_changedfile=:changefile,allow_broadcasts=:broadcast WHERE uid=:uid"; db_query($sql, array(':newfile' => $_POST['fileadded_notify'], ':changefile' => $_POST['fileupdated_notify'], ':broadcast' => $_POST['admin_broadcasts'], ':uid' => $user->uid)); $data['retcode'] = 200; $data['displayhtml'] = theme('filedepot_notifications'); } else { $data['retcode'] = 500; } break; case 'deletenotification': $id = intval($_POST['id']); if ($user->uid > 0 and $id > 0) { db_query("DELETE FROM {filedepot_notifications} WHERE id=:id AND uid=:uid", array(':id' => $id, ':uid' => $user->uid)); $data['retcode'] = 200; $data['displayhtml'] = theme('filedepot_notifications'); } else { $data['retcode'] = 500; } break; case 'clearnotificationlog': db_query("DELETE FROM {filedepot_notificationlog} WHERE target_uid=:uid", array(':uid' => $user->uid)); $data['retcode'] = 200; break; case 'multisubscribe': $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) { $data['retcode'] = 403; // forbidden } elseif ($user->uid > 0) { $reportmode = check_plain($_POST['reportmode']); $fileitems = check_plain($_POST['checkeditems']); $folderitems = check_plain($_POST['checkedfolders']); $filedepot->cid = intval($_POST['cid']); $filedepot->activeview = check_plain($_POST['reportmode']); if (!empty($fileitems)) { $files = explode(',', $fileitems); foreach ($files as $fid) { filedepotAjaxServer_updateFileSubscription($fid, 'add'); } } if (!empty($folderitems)) { $folders = explode(',', $folderitems); foreach ($folders as $cid) { if (db_query("SELECT count(id) FROM {filedepot_notifications} WHERE cid=:cid AND uid=:uid", array(':cid' => $cid, ':uid' => $user->uid))->fetchField() == 0) { $sql = "INSERT INTO {filedepot_notifications} (cid,cid_newfiles,cid_changes,uid,date) "; $sql .= "VALUES (:cid,1,1,:uid,:time)"; db_query($sql, array(':cid' => $cid, ':uid' => $user->uid, ':time' => time())); } } } $data['retcode'] = 200; $data = filedepotAjaxServer_generateLeftSideNavigation($data); $data['displayhtml'] = filedepot_displayFolderListing($filedepot->cid); } else { $data['retcode'] = 500; } break; case 'autocompletetag': $matches = $nexcloud->get_matchingtags($_GET['query']); $retval = implode("\n", $matches); break; case 'refreshtagcloud': $data['retcode'] = 200; $data['tagcloud'] = theme('filedepot_tagcloud'); break; case 'search': $query = $_POST['query']; if (!empty($query)) { $filedepot->activeview = 'search'; $filedepot->cid = 0; $data['retcode'] = 200; $data['displayhtml'] = filedepot_displaySearchListing($query); $data['header'] = theme('filedepot_header'); $data['activefolder'] = theme('filedepot_activefolder'); } else { $data['retcode'] = 400; } break; case 'searchtags': if (isset($_POST['tags'])) { $tags = stripslashes($_POST['tags']); } else { $tags = ''; } if (isset($_POST['removetag'])) { $removetag = stripslashes($_POST['removetag']); } else { $removetag = ''; } $current_search_tags = ''; $filedepot->activeview = 'searchtags'; $filedepot->cid = 0; if (!empty($tags)) { if (!empty($removetag)) { $removetag = stripslashes($removetag); $atags = explode(',', $tags); $key = array_search($removetag, $atags); if ($key !== FALSE) { unset($atags[$key]); } $tags = implode(',', $atags); $_POST['tags'] = $tags; } else { $removetag = ''; } if (!empty($tags)) { $data['searchtags'] = stripslashes($tags); $atags = explode(',', $tags); if (count($atags) >= 1) { foreach ($atags as $tag) { $tag = trim($tag); // added to handle extra space thats added when removing a tag - thats between 2 other tags if (!empty($tag)) { $current_search_tags .= theme('filedepot_searchtag', array('searchtag' => addslashes($tag), 'label' => check_plain($tag))); } } } $data['retcode'] = 200; $data['currentsearchtags'] = $current_search_tags; $data['displayhtml'] = filedepot_displayTagSearchListing($tags); $data['tagcloud'] = theme('filedepot_tagcloud'); $data['header'] = theme('filedepot_header'); $data['activefolder'] = theme('filedepot_activefolder'); } else { unset($_POST['tags']); $filedepot->activeview = 'latestfiles'; $data['retcode'] = 200; $data['currentsearchtags'] = ''; $data['tagcloud'] = theme('filedepot_tagcloud'); $data['displayhtml'] = filedepot_displayFolderListing($filedepot->cid); $data['header'] = theme('filedepot_header'); $data['activefolder'] = theme('filedepot_activefolder'); } } else { $data['tagcloud'] = theme('filedepot_tagcloud'); $data['retcode'] = 203; // Partial Information } break; case 'approvefile': $id = intval($_POST['id']); $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) { $data['retcode'] = 403; // forbidden } elseif ($user->uid > 0 and $filedepot->approveFileSubmission($id)) { $filedepot->cid = 0; $filedepot->activeview = 'approvals'; $data = filedepotAjaxServer_getfilelisting(); $data = filedepotAjaxServer_generateLeftSideNavigation($data); $data['retcode'] = 200; } else { $data['retcode'] = 400; } break; case 'approvesubmissions': $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) { $data['retcode'] = 403; // forbidden } elseif ($user->uid > 0) { $reportmode = check_plain($_POST['reportmode']); $fileitems = check_plain($_POST['checkeditems']); $files = explode(',', $fileitems); $approved_files = 0; $filedepot->activeview = 'approvals'; foreach ($files as $id) { // Check if this is a valid submission record if ($id > 0 and db_query("SELECT COUNT(*) FROM {filedepot_filesubmissions} WHERE id=:id", array(':id' => $id))->fetchField() == 1) { // Verify that user has Admin Access to approve this file $cid = db_query("SELECT cid FROM {filedepot_filesubmissions} WHERE id=:id", array(':id' => $id))->fetchField(); if ($cid > 0 and $filedepot->checkPermission($cid, array('admin', 'approval'), 0, FALSE)) { if ($filedepot->approveFileSubmission($id)) { $approved_files++; } } } } if ($approved_files > 0) { $data['retcode'] = 200; $data = filedepotAjaxServer_generateLeftSideNavigation($data); $data['displayhtml'] = filedepot_displayFolderListing(); } else { $data['retcode'] = 400; } } break; case 'deletesubmissions': $token = isset($_POST['ltoken']) ? $_POST['ltoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_LISTING)) { $data['retcode'] = 403; // forbidden } elseif ($user->uid > 0) { $reportmode = check_plain($_POST['reportmode']); $fileitems = check_plain($_POST['checkeditems']); $files = explode(',', $fileitems); $deleted_files = 0; $filedepot->activeview = 'approvals'; foreach ($files as $id) { // Check if this is a valid submission record if ($id > 0 and db_query("SELECT COUNT(*) FROM {filedepot_filesubmissions} WHERE id=:id", array(':id' => $id))->fetchField() == 1) { // Verify that user has Admin Access to approve this file $cid = db_query("SELECT cid FROM {filedepot_filesubmissions} WHERE id=:id", array(':id' => $id))->fetchField(); if ($cid > 0 and $filedepot->checkPermission($cid, array('admin', 'approval'), 0, FALSE)) { if ($filedepot->deleteSubmission($id)) { $deleted_files++; } } } } if ($deleted_files > 0) { $data['retcode'] = 200; $data = filedepotAjaxServer_generateLeftSideNavigation($data); $data['displayhtml'] = filedepot_displayFolderListing(); } else { $data['retcode'] = 400; } } break; case 'deleteincomingfile': $id = intval($_POST['id']); $message = ''; $token = isset($_POST['token']) ? $_POST['token'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FOLDERMGMT)) { $data['retcode'] = 403; // forbidden } else { $fid = db_query("SELECT drupal_fid FROM {filedepot_import_queue} WHERE id=:id", array(':id' => $id))->fetchField(); if ($fid > 0) { $filepath = db_query("SELECT filepath FROM {files} WHERE fid=:fid", array(':fid' => $fid))->fetchField(); if (!empty($filepath) and file_exists($filepath)) { @unlink($filepath); } db_query("DELETE FROM {files} WHERE fid=:fid", array(':fid' => $fid)); db_query("DELETE FROM {filedepot_import_queue} WHERE id=:id", array(':id' => $id)); $data['retcode'] = 200; $filedepot->activeview = 'incoming'; $data = filedepotAjaxServer_generateLeftSideNavigation($data); $data['displayhtml'] = filedepot_displayFolderListing(); } else { $data['retcode'] = 500; } $retval = json_encode($data); } break; case 'moveincomingfile': //FILEDEPOT_TOKEN_FOLDERMGMT $newcid = intval($_POST['newcid']); $id = intval($_POST['id']); $filedepot->activeview = 'incoming'; $data = array(); $token = isset($_POST['token']) ? $_POST['token'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FOLDERMGMT)) { $data['retcode'] = 403; // forbidden } elseif ($newcid > 0 and $id > 0 and $filedepot->moveIncomingFile($id, $newcid)) { // Send out email notifications of new file added to all users subscribed - Get fileid for the new file record $fid = db_query("SELECT fid FROM {filedepot_files} WHERE cid=:cid AND submitter=:uid ORDER BY fid DESC", array(':cid' => $newcid, ':uid' => $user->uid), 0, 1)->fetchField(); filedepot_sendNotification($fid, FILEDEPOT_NOTIFY_NEWFILE); $data['retcode'] = 200; $data = filedepotAjaxServer_generateLeftSideNavigation($data); $data['displayhtml'] = filedepot_displayFolderListing(); } else { $data['retcode'] = 500; } break; case 'broadcastalert': $data = array(); if (variable_get('filedepot_default_allow_broadcasts', 1) == 0) { $data['retcode'] = 204; } else { $fid = intval($_POST['fid']); $message = check_plain($_POST['message']); $token = isset($_POST['ftoken']) ? $_POST['ftoken'] : NULL; if ($token == NULL || !drupal_valid_token($token, FILEDEPOT_TOKEN_FILEDETAILS)) { $data['retcode'] = 403; } elseif (!empty($message) and $fid > 0) { $data = filedepotAjaxServer_broadcastAlert($fid, $message); } else { $data['retcode'] = 500; } } break; } ob_clean(); if ($action != 'autocompletetag') { if ($action != 'getmorefiledata' and $action != 'getmorefolderdata') { $retval = json_encode($data); } header('Cache-Control: no-store, no-cache, must-revalidate'); header('content-type: application/xml', TRUE); echo "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"; } echo $retval; }
/** * Inits building some sitemap generation stats * * @since 1.3.0 * @access private */ private function _init_stats() { // track sitemap generation time timer_start(); // number of queries used to generate a sitemap $this->build_stats['query'] = get_num_queries(); }
static function Finish() { if (self::$finished) { return; } self::$finished = true; while (ob_get_level() > 3) { ob_end_flush(); } timer_start('Output Template'); utopia::OutputTemplate(); timer_end('Output Template'); if (isset($GLOBALS['timers']) && utopia::DebugMode()) { echo '<pre class="uDebug"><table>'; foreach ($GLOBALS['timers'] as $name => $info) { if (!is_array($info)) { continue; } $time = !array_key_exists('time_taken', $info) ? timer_end($name) : $info['time_taken']; $time = number_format($time, 2); echo '<tr><td style="vertical-align:top;border-top:1px solid black">' . $time . '</td><td style="vertical-align:top;border-top:1px solid black">' . $name . PHP_EOL . $info['info'] . '</td></tr>'; } echo '</table></pre>'; } header('X-Runtime: ' . number_format((microtime(true) - UCORE_START_TIME) * 1000) . 'ms'); die; }
/** * Debug timer * * @ return bool */ private function checkDebug() { // Start timer if debugging if (DEBUG == "true") { timer_start('hotaru'); ini_set('display_errors', 1); // show errors return true; } else { ini_set('display_errors', 0); // hide errors } return false; }