function returnAjax($data)
 {
     /***
      * Return the data as a JSON object
      *
      * @param array $data
      *
      ***/
     if (!is_array($data)) {
         $data = array($data);
     }
     $data["execution_time"] = elapsed();
     header('Cache-Control: no-cache, must-revalidate');
     header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
     header('Content-type: application/json');
     // try {
     //     foreach($data as $col=>$val) {
     //         $clean = deEscape($val);
     //         if(!empty($clean)) $data[$col] = $clean;
     //     }
     // } catch (Exception $e) {
     // }
     $json = json_encode($data, JSON_FORCE_OBJECT);
     $replace_array = array(""", """);
     #$deescaped = htmlspecialchars_decode(html_entity_decode($json));
     #$dequoted = str_replace($replace_array,"\\\"",$deescaped);
     $dequoted_bare = str_replace($replace_array, "\\\"", $json);
     $de2 = htmlspecialchars_decode(html_entity_decode($dequoted_bare));
     #print $deescaped;
     # print $dequoted_bare;
     print $de2;
     #print htmlspecialchars_decode(html_entity_decode(urldecode($json)));
     exit;
 }
示例#2
0
 /** Module initialization */
 public function init(array $params = array())
 {
     // TODO: Add control over tools installation
     // TODO: Add control over tool output/returnval to signal error
     // Get web-application supported images
     foreach ($this->getImagesList($this->supported) as $extension => $images) {
         // Iterate all images with this extension
         foreach ($images as $image) {
             // Generate hash string describing
             $cacheFile = md5($image) . '.' . $extension;
             // Check if cache file has to be updated
             if ($this->cache_refresh($cacheFile, false)) {
                 elapsed('Lossless compressing image: ' . $image);
                 // Dependently on image extension use specific tool for compression
                 switch ($extension) {
                     case 'jpg':
                     case 'jpeg':
                         exec('jpegoptim ' . $image);
                         break;
                     case 'png':
                         exec('optipng -o7 ' . $image);
                         break;
                     default:
                         elapsed('Image:' . $image . ' cannot be compressed, extension not supported');
                 }
                 // Store cached empty image version to avoid duplicate compressing
                 file_put_contents($cacheFile, '');
             }
         }
     }
 }
function disk($file, $value = '§k¥', $duration = '30 days')
{
    global $skyphp_storage_path;
    $file = implode('/', array_filter(explode('/', $file)));
    $cache_file = $skyphp_storage_path . 'diskcache/' . $file;
    //echo 'cachefile: ' . $cache_file . '<br />';
    if ($value == '§k¥') {
        // read
        elapsed("begin disk-read({$file})");
        if (is_file($cache_file) && filesize($cache_file)) {
            // if the file exists, open the file and get the expiration time
            $fh = fopen($cache_file, 'r');
            $value = fread($fh, filesize($cache_file));
            $needle = "\n";
            $break = strpos($value, $needle);
            $expiration_time = substr($value, 0, $break);
            $value = substr($value, $break + strlen($needle));
            fclose($fh);
            if ($expiration_time > time()) {
                // if the file is not expired, return the value
                elapsed("end disk-read({$file})");
                return $value;
            } else {
                // file is expired, delete the file
                elapsed("end disk-read({$file})");
                unlink($cache_file);
            }
        }
        return false;
    } else {
        // write
        elapsed("begin disk-write({$file})");
        // set the value on disk
        $expiration_time = strtotime($duration);
        $value = $expiration_time . "\n" . $value;
        $end = strrpos($cache_file, '/');
        $cache_dir = substr($cache_file, 0, $end);
        //echo 'cachedir: ' . $cache_dir . "<br />";
        @mkdir($cache_dir, 0777, true);
        touch($cache_file);
        $fh = fopen($cache_file, 'w') or die("can't open cache file");
        fwrite($fh, $value);
        fclose($fh);
        elapsed("end disk-write({$file})");
        return true;
    }
}
function returnAjax($data)
{
    /***
     * Return the data as a JSON object
     *
     * @param array $data
     *
     ***/
    if (!is_array($data)) {
        $data = array($data);
    }
    $data["execution_time"] = elapsed();
    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Content-type: application/json');
    $json = json_encode($data, JSON_FORCE_OBJECT);
    $replace_array = array("&quot;", "&#34;");
    print str_replace($replace_array, "\\\"", $json);
    exit;
}
function returnAjax($data)
{
    /***
     * Return the data as a JSON object. This function, when called,
     * will exit the script.
     *
     * @param array $data
     *
     ***/
    if (!is_array($data)) {
        $data = array($data);
    }
    $data['execution_time'] = elapsed();
    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Content-type: application/json');
    $json = json_encode($data, JSON_FORCE_OBJECT);
    $replace_array = array('&quot;','&#34;');
    print str_replace($replace_array, '\\"', $json);
    exit();
}
 function returnAjax($data)
 {
     if (!is_array($data)) {
         $data = array($data);
     }
     $data['execution_time'] = elapsed();
     $data['completed'] = microtime_float();
     global $do;
     $data['requested_action'] = $do;
     $data['args_provided'] = $_REQUEST;
     if (!isset($data['status'])) {
         $data['status'] = false;
         $data['error'] = 'Server returned null or otherwise no status.';
         $data['human_error'] = "Server didn't respond correctly. Please try again.";
         $data['app_error_code'] = -10;
     }
     header('Cache-Control: no-cache, must-revalidate');
     header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
     header('Content-type: application/json');
     global $billingTokens;
     if (is_array($billingTokens)) {
         $data['billing_meta'] = $billingTokens;
     }
     // try {
     //     foreach($data as $col=>$val) {
     //         $data[$col] = deEscape($val);
     //     }
     // } catch (Exception $e) {
     // }
     $json = json_encode($data, JSON_FORCE_OBJECT);
     $replace_array = array("&quot;", "&#34;");
     $deescaped = htmlspecialchars_decode(html_entity_decode($json));
     $dequoted = str_replace($replace_array, "\\\"", $deescaped);
     $dequoted_bare = str_replace($replace_array, "\\\"", $json);
     $de2 = htmlspecialchars_decode(html_entity_decode($dequoted_bare));
     #print $deescaped;
     # print $dequoted_bare;
     print $de2;
     exit;
 }
示例#7
0
 public function getFeed($who, $limit = 50, $offset = 0)
 {
     if (!is_array($who)) {
         $who = array($who);
     }
     $who_array = $who;
     foreach ($who_array as $who) {
         if ($who_csv) {
             $who_csv .= ',';
         }
         $who_csv .= "'{$who}'";
     }
     // return a distinct field in a table with an order by
     $where = "who in ( {$who_csv} )";
     $order_by = 'news_who.insert_time desc';
     $person_id = PERSON_ID ? PERSON_ID : 0;
     $sql = "\n            SELECT news_item_id FROM (\n                SELECT DISTINCT ON (q.news_item_id) news_item_id, row FROM (\n                    SELECT\n                        news_who.news_item_id,\n                        row_number() OVER (ORDER BY {$order_by}) AS row\n                    FROM news_who\n                    LEFT JOIN news_hide on news_hide.news_item_id = news_who.news_item_id\n                        and news_hide.person_id = {$person_id}\n                        and news_hide.active = 1\n                    LEFT JOIN news_item on news_item.id = news_who.news_item_id\n                    WHERE news_who.active = 1\n                    AND news_item.active = 1\n                    AND news_hide.id is null\n                    AND {$where}\n                    ORDER BY {$order_by}\n                    OFFSET {$offset}\n                    LIMIT {$limit}\n                ) AS q\n            ) AS fin ORDER BY row";
     //print_pre($sql);
     elapsed('before news query');
     $arr = sql_array($sql);
     elapsed('after news query');
     return $arr;
 }
示例#8
0
}
$syck_stop = microtime();
$test_str = serialize($test_obj);
$unser_start = microtime();
foreach (range(0, $iter) as $i) {
    $test_obj = unserialize($test_str);
}
$unser_stop = microtime();
$doc2 = "";
foreach (range(0, $iter) as $i) {
    $doc2 .= $doc . "\n";
}
echo "DOC #2 = 1 x " . strlen($doc2) . "\n";
$syck2_start = microtime();
$test_obj = syck_load($doc2);
$syck2_stop = microtime();
$test_str = serialize($test_obj);
$unser2_start = microtime();
$test_obj = unserialize($test_str);
$unser2_stop = microtime();
function elapsed($start, $stop)
{
    $start_mt = explode(" ", $start);
    $stop_mt = explode(" ", $stop);
    $start_total = doubleval($start_mt[0]) + $start_mt[1];
    $stop_total = doubleval($stop_mt[0]) + $stop_mt[1];
    return sprintf("%0.6f", $stop_total - $start_total);
}
echo "syck:  " . elapsed($syck_start, $syck_stop) . " " . elapsed($syck2_start, $syck2_stop) . "\n";
echo "php:   " . elapsed($unser_start, $unser_stop) . " " . elapsed($unser2_start, $unser2_stop) . "\n";
 public function render(array $db_rows = null, $module = null)
 {
     // Rows HTML
     $rows = '';
     // if no rows data is passed - perform db request
     if (!isset($db_rows)) {
         $db_rows = $this->query->exec();
     }
     // If we have table rows data
     if (is_array($db_rows)) {
         // Save quantity of rendering rows
         $this->last_render_count = sizeof($db_rows);
         // Debug info
         $rn = 0;
         $rc = sizeof($db_rows);
         // Iterate db data and perform rendering
         foreach ($db_rows as &$db_row) {
             if ($this->debug) {
                 elapsed('Rendering row ' . $rn++ . ' of ' . $rc . '(#' . $db_row->id . ')');
             }
             $rows .= $this->row($db_row, $this->pager);
             //catch(\Exception $e){ return e('Error rendering row#'.$rn.' of '.$rc.'(#'.$db_row->id.')'); }
         }
     } else {
         $rows .= $this->emptyrow($this->query, $this->pager);
     }
     //elapsed('render pages: '.$this->pager->total);
     // Render table view
     return m($module)->view($this->table_tmpl)->set($this->pager)->rows($rows)->output();
 }
示例#10
0
文件: CMS.php 项目: rmolodyko/cms_api
 public function migrate_8_to_9()
 {
     elapsed('Adding `filter` table');
     elapsed('Adding `filtered` field into `field` table');
     // SQL комманда на создание таблицы фильтров
     $sql_filter = "CREATE TABLE IF NOT EXISTS `" . dbMySQLConnector::$prefix . "filter` (\n\t\t  `filter_id` int(11) NOT NULL AUTO_INCREMENT,\n\t\t  `field_id` int(11) NOT NULL,\n\t\t  `value` varchar(255) NOT NULL,\n\t\t  `locale` VARCHAR( 10 ) NOT NULL,\n\t\t  PRIMARY KEY (`filter_id`)\n\t\t) ENGINE=INNODB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=0 ;";
     db()->query($sql_filter);
     db()->query('ALTER TABLE  `' . dbMySQLConnector::$prefix . 'field` ADD  `filtered` INT( 10 ) NOT NULL AFTER  `local`');
 }
示例#11
0
文件: ide.php 项目: hshoghi/cms
                            class="ide"
                            >
                            <?php 
                    echo $col['table_name'];
                    ?>
 (<?php 
                    echo $count;
                    ?>
)
                        </a>
                    </p>
<?php 
                }
            }
        }
        elapsed('after foreach cols');
    } else {
        echo 'No Data';
    }
} else {
    ?>
        <br /><br />
        <div id="goIde" style="text-align: center;">
            <input type="text" id="ide" name="ide" style="font-size: 2em;"/>
            <input type="button" id="ideGo" value="Go &raquo;" onclick="goIde(this)" style="font-size: 2em;"/>
        </div>
<?php 
}
?>

</div>
 private function generate_nodes($read_db = NULL)
 {
     global $repmgr_cluster_name, $db;
     elapsed("repmgr generate_nodes start");
     $conninfo_host_key = 'host=';
     $sql = "select id, cluster, conninfo, case when strpos(conninfo, '{$conninfo_host_key}') > 0 then substr(conninfo, strpos(conninfo, '{$conninfo_host_key}') + length('{$conninfo_host_key}'), strpos(substr(conninfo, strpos(conninfo, '{$conninfo_host_key}')), ' ') - 1 - length('{$conninfo_host_key}')) else NULL end as host from repmgr_{$repmgr_cluster_name}.repl_nodes where cluster = '{$repmgr_cluster_name}'";
     $unused_nodes = array();
     elapsed('repmgr generate_nodes query 1 start');
     if ($rs = $db->Execute($sql)) {
         elapsed('repmgr generate_nodes query 1 end');
         elapsed('repmgr generate_nodes query 1 start process data');
         while (!$rs->EOF) {
             $unused_nodes[$id = $rs->Fields('id')] = array('id' => $id, 'type' => 'unused', 'host' => $rs->Fields('host'), 'conninfo' => $rs->Fields('conninfo'));
             $rs->MoveNext();
         }
         elapsed('repmgr generate_nodes query 1 end process data');
         unset($rs, $sql, $id);
     }
     if ($read_db == 'localhost') {
         $read_db = trim(rtrim(`hostname`));
     }
     $sql = "select p_nodes.cluster, s_nodes.conninfo as standby_conninfo, p_nodes.conninfo as primary_conninfo, substr(s_nodes.conninfo, strpos(s_nodes.conninfo, '{$conninfo_host_key}') + length('{$conninfo_host_key}'), strpos(substr(s_nodes.conninfo, strpos(s_nodes.conninfo, '{$conninfo_host_key}')), ' ') - 1 - length('{$conninfo_host_key}')) as standby_host, substr(p_nodes.conninfo, strpos(p_nodes.conninfo, '{$conninfo_host_key}') + length('{$conninfo_host_key}'), strpos(substr(p_nodes.conninfo, strpos(p_nodes.conninfo, '{$conninfo_host_key}')), ' ') - 1 - length('{$conninfo_host_key}')) as primary_host, standby_node, primary_node, time_lag from repmgr_{$repmgr_cluster_name}.repl_nodes as s_nodes inner join repmgr_{$repmgr_cluster_name}.repl_status s_status on s_nodes.id = s_status.standby_node inner join repmgr_{$repmgr_cluster_name}.repl_nodes as p_nodes on s_status.primary_node = p_nodes.id where p_nodes.cluster = '{$repmgr_cluster_name}';";
     #       $sql = "select p_nodes.cluster, s_nodes.conninfo as standby_conninfo, p_nodes.conninfo as primary_conninfo, substr(s_nodes.conninfo, strpos(s_nodes.conninfo, '$conninfo_host_key') + length('$conninfo_host_key'), strpos(substr(s_nodes.conninfo, strpos(s_nodes.conninfo, '$conninfo_host_key')), ' ') - 1 - length('$conninfo_host_key')) as standby_host, substr(p_nodes.conninfo, strpos(p_nodes.conninfo, '$conninfo_host_key') + length('$conninfo_host_key'), strpos(substr(p_nodes.conninfo, strpos(p_nodes.conninfo, '$conninfo_host_key')), ' ') - 1 - length('$conninfo_host_key')) as primary_host, standby_node, primary_node from repmgr_$repmgr_cluster_name.repl_nodes as s_nodes inner join (select distinct primary_node, standby_node from repmgr_$repmgr_cluster_name.repl_monitor) as s_status on s_nodes.id = s_status.standby_node inner join repmgr_$repmgr_cluster_name.repl_nodes as p_nodes on s_status.primary_node = p_nodes.id where p_nodes.cluster = '$repmgr_cluster_name';";
     elapsed('repmgr generate_nodes query 2 start');
     if ($rs = $db->Execute($sql)) {
         elapsed('repmgr generate_nodes query 2 end');
         elapsed('repmgr generate_nodes query 2 start process data');
         $primary_nodes = array();
         $standby_nodes = array();
         while (!$rs->EOF) {
             if (!$primary_nodes[$primary_node = $rs->Fields('primary_node')]) {
                 $primary_nodes[$primary_node] = array('id' => $primary_node, 'type' => 'primary', 'host' => $rs->Fields('primary_host'), 'conninfo' => $rs->Fields('primary_conninfo'));
             }
             if (!$standby_nodes[$standby_node = $rs->Fields('standby_node')]) {
                 $standby_nodes[$standby_node] = array('id' => $standby_node, 'type' => 'standby', 'host' => $rs->Fields('standby_host'), 'conninfo' => $rs->Fields('standby_conninfo'), 'roles' => array(array('primary_node_id' => $primary_node, 'time_lag' => $rs->Fields('time_lag'))));
             } else {
                 $standby_nodes[$standby_node]['roles'][] = array('primary_node_id' => $primary_node, 'time_lag' => $rs->Fields('time_lag'));
             }
             if ($standby_nodes[$standby_node]['host'] == $read_db) {
                 $this->set_write_db($primary_nodes[$primary_node]['host']);
                 $this->current_node =& $standby_nodes[$standby_node];
             }
             $rs->MoveNext();
             unset($unused_nodes[$primary_node], $unused_nodes[$standby_node], $primary_node, $standby_node);
         }
         elapsed('repmgr generate_nodes query 2 end process data');
         $this->primary_nodes = $primary_nodes;
         $this->standby_nodes = $standby_nodes;
         $this->unused_nodes = $unused_nodes;
         unset($rs, $sql, $primary_nodes, $standby_nodes, $conninfo_host_key, $unused_nodes);
     } else {
         return NULL;
     }
     elapsed("repmgr generate_nodes end");
     return true;
 }
function get_disp_status($row_in)
{
    // 4/26/11
    extract($row_in);
    $tags_arr = explode("/", get_variable('disp_stat'));
    if (is_date($u2farr)) {
        return "<SPAN CLASS='disp_stat'>&nbsp;{$tags_arr[4]}&nbsp;" . elapsed($u2farr) . "</SPAN>";
    }
    if (is_date($u2fenr)) {
        return "<SPAN CLASS='disp_stat'>&nbsp;{$tags_arr[3]}&nbsp;" . elapsed($u2fenr) . "</SPAN>";
    }
    if (is_date($on_scene)) {
        return "<SPAN CLASS='disp_stat'>&nbsp;{$tags_arr[2]}&nbsp;" . elapsed($on_scene) . "</SPAN>";
    }
    if (is_date($responding)) {
        return "<SPAN CLASS='disp_stat'>&nbsp;{$tags_arr[1]}&nbsp;" . elapsed($responding) . "</SPAN>";
    }
    if (is_date($dispatched)) {
        return "<SPAN CLASS='disp_stat'>&nbsp;{$tags_arr[0]}&nbsp;" . elapsed($dispatched) . "</SPAN>";
    }
}
示例#14
0
<?php

global $website, $cache_refresh;
?>

<section id="list-places"> <!-- state/place list -->
   <a id="markets_list" name="markets_list"></a>
   <span class="list-caption">choose city for your new year's destination</span>
	<nav>
<?php 
$cache_name = sprintf('jwebsite:%/id:markets_footer', $website->ct_promoter_website_id);
if (!$cache_refresh) {
    \elapsed("Footer : Getting the markets from cache");
    $markets = mem($cache_name);
}
if (!$markets) {
    $markets = [];
    $marketIds = \Crave\Model\market::getSlugsFeed(['ct_promoter_website_id' => $website->ct_promoter_website_id, 'where' => ["country_code='US'"], 'order_by' => 'name']);
    foreach ($marketIds as $marketId) {
        $market = new \Crave\Model\Market($marketId);
        if (!$market->country_code) {
            $market->country_code = 'us';
        }
        $market->url = strtolower("/" . $market->slug);
        $markets[] = $market;
    }
    mem($cache_name, $markets, '10 hours');
}
$panels = [];
$delimiter_index = ceil(count($markets) / 6);
$index = -1;
示例#15
0
                $db = &ADONewConnection($db_platform);
                @$db->Connect($db_host, $db_username, $db_password, $db_name);
            
                if ($db->ErrorMsg()) {
                    // connection to the standby failed, try the next one
                    $db_error .= "db error ($db_host): {$db->ErrorMsg()}. \n";
                    continue;
                }
            
                // we connected
                break;
            
            }
            */
        }
    }
    // unset temp connection resource
    unset($d);
    // if the master is our only connection, use it for reads also
    if ($dbw && !$db) {
        $db =& $dbw;
        $db_host = $dbw_host;
    }
    // if we are missing both master and slave, display 503 down for maintenance message
    if (!$db && !$dbw) {
        include 'pages/503.php';
        die("<!-- {$db_error} -->");
    }
}
elapsed('db-connect end');
示例#16
0
 /**
  * Create SQL request
  *
  * @param string $class_name Classname for request creating
  * @param QueryInterface $query Query with parameters
  * @return string SQL string
  */
 protected function prepareSQL($class_name, QueryInterface $query)
 {
     //elapsed( 'dbMySQL::find() Начало');
     $params = $this->__get_table_data($class_name);
     // Получим переменные для запроса
     extract($params);
     // Текст выборки полей
     $select = '`' . $_table_name . '`.*';
     //$_sql_select['this'];
     // If virtual fields defined
     if (sizeof($query->virtual_fields)) {
         $select .= ', ' . "\n" . implode("\n" . ', ', $query->virtual_fields);
     }
     $from = ' ( ' . $this->prepareInnerSQL($class_name, $query, $params);
     // Добавим алиас
     $from .= ' ) as `' . $_table_name . '`';
     //trace($query->join);
     // Iterate related tables
     foreach ($query->join as $relation_data) {
         $c_table = self::$prefix . $relation_data->table;
         // Если существует требуемая связь
         if (isset($_sql_from[$c_table])) {
             // Получим текст для выборки данных из связанных таблиц
             $select .= ',' . $_sql_select[$c_table];
             // Получим текст для привязывания таблицы к запросу
             $from .= "\n" . ' ' . $_sql_from[$c_table];
         } else {
             return e('Ошибка! В таблице связей для класса(##), не указана связь с классом(##)', E_SAMSON_FATAL_ERROR, array($class_name, $c_table));
         }
     }
     // Сформируем строку запроса на поиск записи
     $sql = "\n" . 'SELECT ' . $select . "\n" . ' FROM ' . $from;
     // Получим все условия запроса
     $sql .= "\n" . ' WHERE (' . $this->getConditions($query->condition, $class_name) . ')';
     // Добавим нужные сортировщики
     if (sizeof($query->group)) {
         $sql .= "\n" . ' GROUP BY ' . $query->group[0];
     }
     // Если указана сортировка результатов
     if (sizeof($query->order)) {
         $sql .= "\n" . ' ORDER BY ';
         for ($i = 0; $i < sizeof($query->order); $i++) {
             $item =& $query->order[$i];
             if (sizeof($item)) {
                 $sql .= $item[0] . ' ' . $item[1];
             }
             if ($i < sizeof($query->order) - 1) {
                 $sql .= ', ';
             }
         }
     }
     // Если нужно ограничить к-во записей в выдаче по главной таблице
     if (sizeof($query->limit)) {
         $sql .= "\n" . ' LIMIT ' . $query->limit[0] . (isset($query->limit[1]) ? ',' . $query->limit[1] : '');
     }
     if (isset($GLOBALS['show_sql'])) {
         elapsed($sql);
     }
     return $sql;
 }
示例#17
0
文件: Client.php 项目: hshoghi/cms
 public static function getFolder($id, $params = null)
 {
     if (!is_array($params)) {
         $params = array();
     }
     global $cache_vf2_folders;
     static::checkForClient();
     $new_params = static::prepOperations($params['width'], $params['height'], $params['crop']);
     $params = array_merge($params, $new_params);
     $memkey = "vf2:getFolder:" . serialize(array($id, $params));
     if ($cache_vf2_folders) {
         if (!$_GET['vf_refresh']) {
             $re = mem($memkey);
         }
         // if there has been an upload to this folder since being cached, refresh it
         $last_upload_memkey = "vf2:getFolder:lastUpload:" . $id;
         $last_upload = mem($last_upload_memkey);
         if (!$re->cache_time || $re->cache_time < $last_upload) {
             elapsed($re->cache_time . ' < ' . $last_upload);
             $re = null;
         } else {
             elapsed($re->cache_time . ' !< ' . $last_upload);
         }
     }
     if (!$re) {
         // connect to vf server only 10% of the time
         //if (rand(0,9) != 9) {
         //    return (object) array();
         //}
         $re = !static::isPath($id) ? static::getClient()->getFolder($id, $params) : static::getClient()->getFolderByPath(array_merge($params, array('path' => $id)));
         $save_to_mem = true;
     }
     if ($re->folder) {
         if ($save_to_mem) {
             $re->cache_time = date('U');
             mem($memkey, $re);
         }
         return $re->folder;
     }
     // cache the error for 1 minute to give some relief to vf server
     // only if this isn't already cached
     if (!$re->cache_time) {
         $re->cache_time = date('U');
         mem($memkey, $re, static::$error_cache_duration);
     }
     return $re;
 }
function showMessagesForMailbox($imapConnection, $mailbox, $num_msgs, $start_msg, $sort, $color, $show_num, $use_cache, $mode = '')
{
    global $msgs, $msort, $auto_expunge, $thread_sort_messages, $allow_server_sort, $server_sort_order;
    /*
     * For some reason, on PHP 4.3+, this being unset, and set in the session causes havoc
     * so setting it to an empty array beforehand seems to clean up the issue, and stopping the
     * "Your script possibly relies on a session side-effect which existed until PHP 4.2.3" error
     */
    if (!isset($msort)) {
        $msort = array();
    }
    if (!isset($msgs)) {
        $msgs = array();
    }
    $start = microtime();
    /* If autoexpunge is turned on, then do it now. */
    $mbxresponse = sqimap_mailbox_select($imapConnection, $mailbox);
    $srt = $sort;
    /* If autoexpunge is turned on, then do it now. */
    if ($auto_expunge == true) {
        $exp_cnt = sqimap_mailbox_expunge($imapConnection, $mailbox, false, '');
        $mbxresponse['EXISTS'] = $mbxresponse['EXISTS'] - $exp_cnt;
        $num_msgs = $mbxresponse['EXISTS'];
    }
    if ($mbxresponse['EXISTS'] > 0) {
        /* if $start_msg is lower than $num_msgs, we probably deleted all messages
         * in the last page. We need to re-adjust the start_msg
         */
        if ($start_msg > $num_msgs) {
            $start_msg -= $show_num;
            if ($start_msg < 1) {
                $start_msg = 1;
            }
        }
        /* This code and the next if() block check for
         * server-side sorting methods. The $id array is
         * formatted and $sort is set to 6 to disable
         * SM internal sorting
         */
        if ($thread_sort_messages == 1) {
            $mode = 'thread';
        } elseif ($allow_server_sort == 1) {
            $mode = 'serversort';
        } else {
            $mode = '';
        }
        sqsession_unregister('msort');
        sqsession_unregister('msgs');
        switch ($mode) {
            case 'thread':
                $id = get_thread_sort($imapConnection);
                $msgs = getServerMessages($imapConnection, $start_msg, $show_num, $num_msgs, $id);
                if ($msgs === false) {
                    echo '<b><small><center><font color=red>' . _("Thread sorting is not supported by your IMAP server.<br>Please report this to the system administrator.") . '</center></small></b>';
                    $thread_sort_messages = 0;
                    $msort = $msgs = array();
                } else {
                    $msort = $msgs;
                    $sort = 6;
                }
                break;
            case 'serversort':
                $id = sqimap_get_sort_order($imapConnection, $sort, $mbxresponse);
                $msgs = getServerMessages($imapConnection, $start_msg, $show_num, $num_msgs, $id);
                if ($msgs === false) {
                    echo '<b><small><center><font color=red>' . _("Server-side sorting is not supported by your IMAP server.<br>Please report this to the system administrator.") . '</center></small></b>';
                    $sort = $server_sort_order;
                    $allow_server_sort = FALSE;
                    $msort = $msgs = array();
                    $id = array();
                } else {
                    $msort = $msgs;
                    $sort = 6;
                }
                break;
            default:
                if (!$use_cache) {
                    $msgs = getSelfSortMessages($imapConnection, $start_msg, $show_num, $num_msgs, $sort, $mbxresponse);
                    $msort = calc_msort($msgs, $sort);
                }
                /* !use cache */
                break;
        }
        // switch
        sqsession_register($msort, 'msort');
        sqsession_register($msgs, 'msgs');
    }
    /* if exists > 0 */
    $res = getEndMessage($start_msg, $show_num, $num_msgs);
    $start_msg = $res[0];
    $end_msg = $res[1];
    $paginator_str = get_paginator_str($mailbox, $start_msg, $end_msg, $num_msgs, $show_num, $sort);
    $msg_cnt_str = get_msgcnt_str($start_msg, $end_msg, $num_msgs);
    do_hook('mailbox_index_before');
    echo '<table border="0" width="100%" cellpadding="0" cellspacing="0">';
    echo '<tr><td>';
    mail_message_listing_beginning($imapConnection, $mailbox, $sort, $msg_cnt_str, $paginator_str, $start_msg);
    echo '</td></tr>';
    /* line between the button area and the list */
    echo '<tr><td HEIGHT="5" BGCOLOR="' . $color[4] . '"></td></tr>';
    echo '<tr><td>';
    echo '    <table width="100%" cellpadding="1" cellspacing="0" align="center" border="0" bgcolor="' . $color[9] . '">';
    echo '     <tr><td>';
    echo '       <table width="100%" cellpadding="1" cellspacing="0" align="center" border="0" bgcolor="' . $color[5] . '">';
    echo '<tr><td>';
    printHeader($mailbox, $srt, $color, !$thread_sort_messages);
    displayMessageArray($imapConnection, $num_msgs, $start_msg, $msort, $mailbox, $sort, $color, $show_num, 0, 0);
    echo '</td></tr></table></td></tr></table>';
    mail_message_listing_end($num_msgs, $paginator_str, $msg_cnt_str, $color);
    echo '</td></tr></table>';
    $t = elapsed($start);
    //echo("elapsed time = $t seconds\n");
}
示例#19
0
/**
 * asPGraph($img, $end, $span)
 *
 * $img  - name of the png to generate
 * $end  - end time in seconds
 * $span - string either "daily", "weekly", "monthly", or "yearly"
 *
 * Build a graph of clean or "Passed" emails.
 * Returns either a html-valid <img> tag which can be printed, or the
 * boolean "false" if something went wrong.
 */
function asPGraph($img, $end, $span)
{
    global $libdir, $virus, $debug, $refresh, $span, $as_pkg, $host_list;
    global $rate, $as_version, $rrdstep, $host, $msgs, $show_graph_period;
    /*
     * Work out the beginning and the end, based on the span
     */
    $limits = getlimits($end, $span);
    $end = $limits["end"];
    $start = $limits["start"];
    $length = $end - $start;
    $timetext = $limits["description"];
    $start_period = strftime("%A %B %d %H:%M:%S (GMT%z)", $start);
    $end_period = strftime("%A %B %d %H:%M:%S (GMT%z)", $end);
    $startdate = strftime("%c", $start);
    $enddate = strftime("%c", $end);
    $nowdate = strftime("%c", time());
    $hostname = on_host($host);
    if ($rate == 60) {
        $ratemsg = "min";
    } else {
        $rate = 3600;
        $ratemsg = "hour";
    }
    $arrcol = array("Passed SPAM" => "7a5aff", "Blocked SPAM" => "fa5aff", "Passed BANNED" => "cc9900", "Blocked BANNED" => "ffdd00", "Passed BAD-HEADER" => "3f00cc", "Blocked BAD-HEADER" => "594e61", "Passed INFECTED" => "9900aa", "Blocked INFECTED" => "ff3a3d", "Passed CLEAN" => "10d0d0", "Blocked CLEAN" => "7ffa00");
    /*
     * It is a two-step process to build the final graph. The average over
     * a specific time period seems to be impossible to get without actually
     * building a graph. Ie, rrd fetch will not calculate the values we
     * need - we would have to sum and average manually.
     *
     * However the PRINT function of a graph will return what we want
     * in an array. So first of all build a graph that PRINTs the average
     * of every virus over the selected time period.
     */
    $opts = array();
    $opts[] = "--start={$start}";
    $opts[] = "--end={$end}";
    foreach ($msgs as $id => $name) {
        $opts[] = "DEF:v{$id}={$libdir}/{$id}.rrd:hits:AVERAGE";
        $opts[] = "CDEF:gv{$id}=v{$id},UN,0,v{$id},IF";
        $opts[] = "CDEF:gvt{$id}=gv{$id},{$length},*";
        $opts[] = "PRINT:gvt{$id}:AVERAGE:%.0lf";
    }
    $ret = pre_graph($img, $opts, count($opts));
    if (!is_array($ret)) {
        $msg = rrd_error();
        asErr("rrd_graph()1: {$msg}");
        return false;
    }
    /*
     * All results from PRINT commands are in the array $ret["calcpr"][..]
     */
    $i = 0;
    $pcount = array();
    foreach ($msgs as $id => $name) {
        /*
         * We don't have enough resolution in the rrds
         * to calculate the correct counts at low averages,
         * so we just don't display them
         */
        if ($ret["calcpr"][$i] != 0) {
            $pcount[$id] = $ret["calcpr"][$i];
        }
        $i++;
    }
    if (count($pcount) >= 1) {
        arsort($pcount);
    } else {
        aslog("pcount is an empty array");
    }
    aslog($pcount, 0, 'pcount');
    $opts = array();
    $opts[] = "--start={$start}";
    $opts[] = "--end={$end}";
    $opts[] = "--imgformat=PNG";
    $opts[] = "--title=Message Breakdown {$hostname}({$timetext} to {$enddate})";
    $opts[] = "--width=580";
    $opts[] = "--vertical-label=msgs/{$ratemsg}";
    $type = "AREA";
    foreach ($pcount as $id => $count) {
        $name = sprintf("%-21s", $msgs[$id]);
        $col = $arrcol[$msgs[$id]];
        $opts[] = "DEF:v{$id}={$libdir}/{$id}.rrd:hits:AVERAGE";
        // rrd datasrc
        $opts[] = "CDEF:gv{$id}=v{$id},UN,0,v{$id},IF";
        // make UNK=0
        $opts[] = "CDEF:gtvt{$id}=gv{$id},{$rate},*";
        // height/rate
        $opts[] = "{$type}:gtvt{$id}#{$col}:{$name} ";
        // name&graph
        $opts[] = "CDEF:gvt{$id}=gv{$id},{$length},*";
        // how many?
        $opts[] = "GPRINT:gvt{$id}:AVERAGE:%.0lf";
        // how many?
        $opts[] = "COMMENT:\\n";
        $type = "STACK";
    }
    $opts[] = "COMMENT:\\n";
    if ($show_graph_period) {
        $opts[] = graph_date($start_period, $end_period);
    }
    $opts[] = "COMMENT:{$as_pkg} v{$as_version}\\r";
    $start = microtime();
    $ret = pre_graph($img, $opts, count($opts));
    $t = elapsed($start);
    if (!is_array($ret)) {
        $err = rrd_error();
        asErr("rrd_graph()2: {$err}");
        return false;
    }
    return "<img class=\"2\" src=\"{$img}\" alt=\"[image: {$timetext}]\">";
}
function authorizeApp($authenticationInformation)
{
    /***
     * Primary wrapper function for everything not directly login / auth
     * related.
     *
     * @param array $authenticationInformation
     *
     * $authenticationInformation should be an array containing the
     * following keys:
     *
     * @key "auth" - the SHA1 hash of "entropy", server secret key, "action", "app_version"
     * @key "key"  - The encryption key to decrypt the server secret key
     * @key "app_version" - the application version number
     * @key "entropy" - A randomly generated string of 16 characters
     * @key "action" - The action to be executed
     * @key "data" - A base64-encoded JSON object with structured data for
     * the action
     * @key "user_id" - the dblink for the user. This will always be
     * appended to the values in the "data" key.
     ***/
    if (is_array($authenticationInformation)) {
        $auth = $authenticationInformation['auth'];
        $auth_key = $authenticationInformation['key'];
        $version = $authenticationInformation['app_version'];
        $entropy = $authenticationInformation['entropy'];
        $action = $authenticationInformation['action'];
        $user = $authenticationInformation['user_id'];
        $device = $authenticationInformation['device_identifier'];
        $action_data = smart_decode64($authenticationInformation['data']);
        if (!is_array($action_data)) {
            returnAjax(array('status' => false, 'human_error' => 'The application and server could not communicate. Please contact support.', 'error' => 'Invalid data object', 'app_error_code' => 101));
        } else {
            # Check structure of variables
            try {
                # Reserved for specific data-type checking
            } catch (Exception $e) {
                returnAjax(array('status' => false, 'human_error' => 'The application and server could not communicate. Please contact support.', 'error' => $e->getMessage(), 'app_error_code' => 108));
            }
            # Save variables to be used later
            $action_data['dblink'] = $user;
            $app_verify = array('device' => $device, 'authorization_token' => $auth, 'auth_prepend' => $entropy, 'auth_postpend' => $action . $version, 'appsecret_key' => $auth_key, 'dblink' => $user);
            $action_data['application_verification'] = $app_verify;
            $u = new UserFunctions($user);
        }
    } else {
        returnAjax(array('status' => false, 'human_error' => 'The application and server could not communicate. Please contact support.', 'error' => 'Invalid request', 'app_error_code' => 102));
    }
    /***
     * See if the action is a valid action.
     * Most of these are just going to be wrappers for the
     * async_login_handler functions.
     ***/
    if (empty($action)) {
        $action = 'sync';
    }
    $action_function_map = array('save' => 'saveToUser', 'read' => 'getFromUser', 'sync' => 'syncUserData');
    if (!array_key_exists($action, $action_function_map)) {
        returnAjax(array('status' => false, 'human_error' => 'The application and server could not communicate. Please contact support.', 'error' => 'Invalid action', 'app_error_code' => 103));
    }
    # See if the user exists
    # get the key for $user from the server
    /***
     * Now, we want to authenticate the app against this information.
     * $auth should be the SHA1 hash of:
     *
     * $auth = sha1($entropy.$SERVER_KEY.$action.$version)
     *
     * If it isn't, the request is bad.
     ***/
    $r = $u->verifyApp($app_verify);
    if (!$r['status']) {
        returnAjax(array('status' => false, 'human_error' => "This app isn't authorized. Please log out and log back in.", 'error' => 'Invalid app credentials', 'app_error_code' => 106));
    }
    # Call the $action
    $action_data['user_data'] = $r['data'];
    $action_result = $action_function_map[$action]($action_data);
    $action_result['elapsed'] = elapsed();
    returnAjax($action_result);
}
示例#21
0
文件: Client.php 项目: hshoghi/cms
 /**
  * Makes the request to the API via cURL and the arguments given
  * @param   string  $url
  * @param   array   $post
  * @param   array   $extra  extra curloptions, so far only HTTPHEADER supported
  * @return  \stdClass
  */
 protected function makeRequest($url, $post = array(), $opts = array())
 {
     global $vfolder_path;
     //d($url, $post, $opts);
     if ($post == "v2") {
         $config = $opts['config'];
         if ($config['crop'] === false) {
             $config['crop'] = 0;
         }
         if ($config['resize'] === false) {
             $config['resize'] = 0;
         }
         //$params = $opts['venue_ide'] ."/".$opts['filename']."/".implode("/",$config)."/".$opts['type']."/".$opts['flyer_type'];
         //d($config, $params);
         //$url = $vfolder_path."/v3/items/".$params."?oauth_token=mytoken";
         $url = $vfolder_path . "/v3/items/get/?oauth_token=mytoken";
         //$url = "http://localdev.vfolder.com/v3/items/".$params."?oauth_token=mytoken";
     } else {
         $url = $this->getRequestUrl($url);
     }
     $curl = curl_init($url);
     //d($curl);
     if ($opts['HTTPHEADER']) {
         if (!curl_setopt($curl, CURLOPT_HTTPHEADER, $opts['HTTPHEADER'])) {
             static::handleCurlError($curl, 'CURLOPT_HTTPHEADER');
         }
     }
     if ($post == "v2") {
         $v2post['method'] = "item";
         $v2post['ide'] = $opts['ide'];
         $v2post['filename'] = $opts['filename'];
         $v2post['config'] = json_encode($config);
         $v2post['type'] = $opts['type'];
         $v2post['flyer_type'] = $opts['flyer_type'];
         $v2post['folder'] = $opts['folder'];
     }
     $curl_timeout = 100;
     if ($_GET['curl_timeout']) {
         $curl_timeout = $_GET['curl_timeout'];
     }
     // make sure these ints are defined
     // you need curl version 7.16.2 for this to work:
     // define('CURLOPT_TIMEOUT_MS', 155);
     // define('CURLOPT_CONNECTTIMEOUT_MS', 156);
     if (!curl_setopt($curl, CURLOPT_TIMEOUT, $curl_timeout)) {
         static::handleCurlError($curl, 'CURLOPT_TIMEOUT');
     }
     if (!curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $curl_timeout)) {
         static::handleCurlError($curl, 'CURLOPT_CONNECTTIMEOUT');
     }
     if (!curl_setopt($curl, CURLOPT_POST, true)) {
         static::handleCurlError($curl, 'CURLOPT_POST');
     }
     if ($post == "v2") {
         if (!curl_setopt($curl, CURLOPT_POSTFIELDS, $v2post)) {
             static::handleCurlError($curl, 'CURLOPT_POSTFIELDS');
         }
     } else {
         if (!curl_setopt($curl, CURLOPT_POSTFIELDS, $post)) {
             static::handleCurlError($curl, 'CURLOPT_POSTFIELDS');
         }
     }
     if (!curl_setopt($curl, CURLOPT_RETURNTRANSFER, true)) {
         static::handleCurlError($curl, 'CURLOPT_RETURNTRANSFER');
     }
     $name = '\\VF\\Client::makeRequest: ' . $url;
     elapsed('begin ' . $name);
     if ($_GET['vf_debug']) {
         echo $url . '<br />POST:';
         krumo($post);
     }
     $response = curl_exec($curl);
     elapsed('end ' . $name);
     $error = curl_error($curl);
     //d($response, $error);
     curl_close($curl);
     if ($error) {
         // there was a curl transmission error
         return (object) array('request' => array('url' => $url, 'post' => $post), 'errors' => array($error));
     }
     $data = json_decode($response);
     if (!$data) {
         // the server did not respond with valid json
         // return the unformatted output as an error
         // there was a curl transmission error
         $data = (object) array('request' => array('url' => $url, 'post' => $post), 'errors' => array($response));
     }
     if ($_GET['vf_debug']) {
         echo 'response:<br />';
         krumo($data);
         echo '<br />';
     }
     //d($data);
     return $data;
 }
示例#22
0
 /**
  * Directly read from memcache
  * Only use this if avoiding transaction reads
  * Otherwise use \Sky\Memcache::get()
  * @param   mixed   $key    one key or an array of keys
  * @return  mixed           value for one key, or an associative array of key => vals
  */
 public static function readMemValue($key)
 {
     if (!static::isMemcacheEnabled() || !$key) {
         return null;
     }
     $fkey = static::getAppSpecificKey($key);
     $read_key = is_array($fkey) ? array_values($fkey) : $fkey;
     \elapsed("begin mem-read({$key})");
     $value = static::getMemcache()->get($read_key);
     \elapsed("end mem-read({$key}");
     if (is_array($key)) {
         $c = $value;
         $value = array();
         foreach ($fkey as $k => $actual) {
             $value[$k] = $c[$actual];
         }
     }
     return $value;
 }
示例#23
0
 /**
  * Compress web-application
  * @param boolean $debug Disable errors output
  * @param string $php_version PHP version to support
  */
 public function compress($debug = false, $environment = 'prod', $php_version = PHP_VERSION)
 {
     // Set compressed project environment
     $this->environment = $environment;
     elapsed('Started web-application compression[' . $this->environment . ']');
     s()->async(true);
     ini_set('memory_limit', '256M');
     // Check output path
     if (!isset($this->output[0])) {
         return $this->log('Cannot compress web-application from [##] - No output path is specified', $this->input);
     }
     // Define rendering model depending on PHP version
     $php_version = isset($php_version[0]) ? $php_version : PHP_VERSION;
     if (version_compare($php_version, '5.3.0', '<')) {
         $this->view_mode = Core::RENDER_ARRAY;
     }
     // Add url base to path
     $this->output .= url()->base();
     // Creating output project folder
     $result = \samson\core\File::mkdir($this->output);
     if ($result) {
         $this->log('Created output project folder [##]', $this->output);
     } else {
         if ($result == -1) {
             return $this->log('Compression failed! Cannot create output project folder [##]', $this->output);
         }
     }
     // Remove all trailing slashes
     $this->output = realpath($this->output) . '/';
     $this->log('[##]## Compressing web-application[##] from [##] to [##]', $environment, $debug ? '[DEBUG]' : '', $php_version, $this->input, $this->output);
     // Add generic composer auto loader require
     $this->php['__before_all']['composer'] = "\n" . 'if(file_exists("vendor/autoload.php")) require "vendor/autoload.php";';
     // Define global views collection
     $this->php[self::NS_GLOBAL][self::VIEWS] = "\n" . '$GLOBALS["__compressor_files"] = array();';
     // If resourcer is loaded - copy css and js
     // Link
     $rr =& s()->module_stack['resourcer'];
     // Iterate all css and js resources
     $ignoreFolders = array();
     foreach ($this->ignoredFolders as $folder) {
         $ignoreFolders[] = $this->output . $folder;
     }
     // Remove all old javascript and css
     \samson\core\File::clear($this->output, array('js', 'css'), $ignoreFolders);
     $moduleListArray = [];
     //$moduleListArray[Router::I_MAIN_PROJECT_TEMPLATE] = $this->system->module_stack;
     Event::fire(self::E_CREATE_MODULE_LIST, array(&$moduleListArray));
     $resource = new Resource($this->fileManager);
     foreach ($moduleListArray as $template => $moduleList) {
         $resourceUrls = [];
         Event::fire(self::E_CREATE_RESOURCE_LIST, array(&$resourceUrls, $moduleList));
         foreach ($resourceUrls as $type => $urls) {
             $file = $resource->compress($urls, $type, $this->output);
             $this->resourceUrlsList[$template][$type] = [DIRECTORY_SEPARATOR . $file];
         }
     }
     // Iterate core ns resources collection
     foreach (s()->module_stack as $id => &$module) {
         // Work only with compressable modules
         if (is_a($module, ns_classname('CompressInterface', 'samsonframework\\core')) || isset($this->composerParameters['samsonphp_package_compressable']) && ($this->composerParameters['samsonphp_package_compressable'] = 1)) {
             $this->compress_module($module, $module->resourceMap);
         }
         // Change path to local modules
         if (is_a($module, '\\samson\\core\\VirtualModule')) {
             $module->path('');
         }
     }
     /*foreach ($rr->cached['js'] as $jsCachedFile) {
                 // Manage javascript resource
                 $javascriptManager = new resource\JavaScript($this);
                 $javascriptManager->compress(__SAMSON_CWD__ . $jsCachedFile, $this->output . basename($jsCachedFile));
             }
     
             foreach ($rr->cached['css'] as $cssCachedFile) {
                 // Manage CSS resource
                 $cssManager = new resource\CSS($this, $rr);
                 $cssManager->compress(__SAMSON_CWD__ . $cssCachedFile, $this->output . basename($cssCachedFile));
             }*/
     //}
     // Copy main project composer.json
     $composerPath = __SAMSON_CWD__ . 'composer.json';
     if (file_exists($composerPath)) {
         // Read json file
         $composerJSON = (array) json_decode(file_get_contents($composerPath));
         // Remove development dependencies
         unset($composerJSON['require-dev']);
         // Remove autoload section
         unset($composerJSON['autoload']);
         // Remove install/update scripts
         unset($composerJSON['scripts']);
         // Write modified composer.json
         file_put_contents($this->output . 'composer.json', json_encode($composerJSON));
     }
     // Set errors output
     $this->php[self::NS_GLOBAL][self::VIEWS] .= "\n" . '\\samson\\core\\Error::$OUTPUT = ' . (!$debug ? 'false' : 'true') . ';';
     // Create SamsonPHP core compressor
     $core = new \samsonphp\compressor\Core(s(), $environment, $this);
     // Add global base64 serialized core string
     $this->php[self::NS_GLOBAL][self::VIEWS] .= "\n" . '$GLOBALS["__CORE_SNAPSHOT"] = \'' . $core->compress() . '\';';
     // Add all specified requires
     foreach ($this->require as $require) {
         $this->php[self::NS_GLOBAL][self::VIEWS] .= "\n" . 'require("' . $require . '");';
     }
     // Add localization data
     $locale_str = array();
     foreach (\samson\core\SamsonLocale::$locales as $locale) {
         if ($locale != '') {
             $locale_str[] = '\'' . $locale . '\'';
         }
     }
     // Add [setlocales] code
     $this->php[self::NS_GLOBAL][self::VIEWS] .= "\n" . 'setlocales( ' . implode(',', $locale_str) . ');';
     // TODO: add generic handlers to modules to provide compressing logic for each module
     // TODO: add generic constants namespace to put all constants definition there - and put only defined constrat and redeclare them
     // TODO: WTF???? Thi must be local module logic
     // If this is remote web-app - collect local resources
     if (__SAMSON_REMOTE_APP) {
         // Gather all resources
         $path = __SAMSON_CWD__;
         $ls = array();
         s()->resources($path, $ls);
         // If we have any resources
         if (isset($ls['resources'])) {
             $this->copy_path_resources($ls['resources'], __SAMSON_CWD__, '');
         }
     }
     // If default locale is defined
     if (!defined('DEFAULT_LOCALE')) {
         define('DEFAULT_LOCALE', 'ru');
     }
     // Add default system locale to them end of core definition
     $this->php['samson\\core'][self::VIEWS] = "\n" . 'define("DEFAULT_LOCALE", "' . DEFAULT_LOCALE . '");';
     // Pointer to entry script code
     $entryScriptPath = __SAMSON_CWD__ . __SAMSON_PUBLIC_PATH . 'index.php';
     $entryScript =& $this->php[self::NS_GLOBAL][$entryScriptPath];
     // Collect all event system data
     $eventCompressor = new EventCompressor();
     $eventCompressor->collect($entryScript);
     // Remove standard framework entry point from index.php	- just preserve default controller
     if (preg_match('/start\\(\\s*(\'|\\")(?<default>[^\'\\"]+)/i', $entryScript, $matches)) {
         /*
          * Temporary solution to support compressed version, because other way localization does not work,
          * as chain is broken, first time URL object is created and URL is parsed only after start, so
          * CMS::afterCompress does not knows what is current locale and does not inject it to all material
          * queries.
          */
         $this->php[self::NS_GLOBAL][self::VIEWS] .= "\n" . 'url();';
         $this->php[self::NS_GLOBAL][self::VIEWS] .= "\n" . 's()->start(\'' . $matches['default'] . '\');';
     } else {
         e('Default module definition not found - possible errors at compressed version');
     }
     // Clear default entry point
     unset($this->php[self::NS_GLOBAL][$entryScriptPath]);
     // Set global namespace as last
     $global_ns = $this->php[self::NS_GLOBAL];
     unset($this->php[self::NS_GLOBAL]);
     $this->php[self::NS_GLOBAL] = $global_ns;
     // Set view data to the end of global namespace
     $s = $this->php[self::NS_GLOBAL][self::VIEWS];
     unset($this->php[self::NS_GLOBAL][self::VIEWS]);
     $this->php[self::NS_GLOBAL][self::VIEWS] = $s;
     // Load all OOP entities
     $classes = array();
     // Соберем коллекцию загруженных интерфейсов их файлов по пространствам имен
     $this->classes_to_ns_files(get_declared_interfaces(), $classes);
     // Соберем коллекцию загруженных классов их файлов по пространствам имен
     $this->classes_to_ns_files(get_declared_classes(), $classes);
     // Fix OOP entities
     foreach ($this->php as $ns => &$files) {
         // If this namespace has been loaded
         if (isset($classes[$ns])) {
             // Fill namespace entities, make OOP entities correct order
             $files = array_merge($classes[$ns], $files);
         }
     }
     // Соберем весь PHP код в один файл
     $index_php = $this->code_array_to_str($this->php, $this->view_mode == 2);
     // Collect all event system data
     $eventCompressor->collect($index_php);
     // Transform event system in all project code
     if ($eventCompressor->transform($index_php, $index_php)) {
         //trace($eventCompressor->subscriptions, true);
     }
     // Remove url_base parsing and put current url base
     if (preg_match('/define\\(\'__SAMSON_BASE__\',\\s*([^;]+)/i', $index_php, $matches)) {
         $index_php = str_replace($matches[0], 'define(\'__SAMSON_BASE__\',\'' . __SAMSON_BASE__ . '\');', $index_php);
     }
     // Set global constant to specify supported PHP version
     if (preg_match('/define\\s*\\(\'__SAMSON_PHP_OLD[^;]+/', $index_php, $matches)) {
         $index_php = str_replace($matches[0], 'define(\'__SAMSON_PHP_OLD\',\'' . ($this->view_mode == 2) . '\');', $index_php);
     }
     $index_php = $this->removeBlankLines($index_php);
     $index_php = preg_replace('/(declare *\\( *strict_types *= *1 *\\) *;)/i', ' ', $index_php);
     // Запишем пусковой файл
     file_put_contents($this->output . 'index.php', '<?php ' . $index_php . "\n" . '?>');
     // Minify PHP code if no debug is needed
     if (!$debug) {
         file_put_contents($this->output . 'index.php', php_strip_whitespace($this->output . 'index.php'));
     }
     elapsed('Site has been successfully compressed to ' . $this->output);
 }
示例#24
0
 /**
  * Create static HTML site version
  */
 public function compress()
 {
     // If no output path specified
     if (!isset($this->output[0])) {
         $this->output = __SAMSON_PUBLIC_PATH . '/out/';
     }
     // Create output directory and clear old HTML data
     if (\samson\core\File::mkdir($this->output)) {
         \samson\core\File::clear($this->output);
     }
     // Save original output path
     $o_output = $this->output;
     elapsed('Creating static HTML web-application from: ' . $this->input . ' to ' . $this->output);
     // Collection of existing generated views
     $views = '<h1>#<i>' . $_SERVER['HTTP_HOST'] . '</i> .html pages:</h1>';
     $views .= 'Generated on ' . date('d M Y h:i');
     // Path to new resources
     $cssPath = '';
     $jsPath = '';
     // Copy generated css & js resources to root folder
     if (class_exists('\\samson\\resourcer\\ResourceRouter')) {
         $rr = m('resourcer');
         // Get resourcer CSS generated files
         $cssPath = $this->input . $rr->cached['css'];
         if (isset($cssPath)) {
             elapsed('Creating CSS resource file from:' . $cssPath);
             // Read CSS file
             $css = file_get_contents($cssPath);
             // Perform URL rewriting
             $css = preg_replace_callback('/url\\s*\\(\\s*(\'|\\")?([^\\)\\s\'\\"]+)(\'|\\")?\\s*\\)/i', array($this, 'srcReplaceCallback'), $css);
             //$css = preg_replace('url((.*?)=si', '\\www', $css);
             $css = str_replace('url("fonts/', 'url("www/fonts/', $css);
             $css = str_replace('url("img/', 'url("www/img/', $css);
             // Write new CSS file
             file_put_contents($this->output . 'style.css', $css);
         }
         // Get resourcer JS generated files
         $jsPath = $rr->cached['js'];
         if (isset($jsPath)) {
             elapsed('Creating JavaScript resource file from:' . $jsPath);
             $this->copy_resource($this->input . $jsPath, $this->output . 'index.js');
         }
     }
     // Iterate all site supported locales
     foreach (\samson\core\SamsonLocale::$locales as $locale) {
         // Generate localized path to cached html pages
         $pages_path = $this->cache_path . locale_path($locale);
         // Set views locale description
         $views .= '<h2>Locale <i>' . ($locale == \samson\core\SamsonLocale::DEF ? 'default' : $locale) . '</i>:<h2>';
         // Get original output path
         $this->output = $o_output;
         //создаем набор дескрипторов cURL
         $mh = curl_multi_init();
         //$__modules = array('local', 'account', 'clients', 'dashboard', 'login', 'main', 'notification', 'project', 'sidebar', 'translators');
         $system_methods = array('__construct', '__sleep', '__destruct', '__get', '__set', '__call', '__wakeup');
         //handler
         // TODO: this is not should be rewritten to support new router
         // Perform generation of every controller
         foreach (s()->module_stack as $id => $ctrl) {
             $rmController = sizeof($ctrl->resourceMap->controllers) ? $ctrl->resourceMap->controllers : $ctrl->resourceMap->module;
             //trace($rmController, 1);
             $controller = array();
             //trace($controller, true);
             if (isset($rmController[0]) && class_exists($rmController[0])) {
                 if (!substr_count($rmController[1], 'vendor')) {
                     $methods = get_class_methods($rmController[0]);
                     foreach ($methods as $method) {
                         if (!in_array($method, $system_methods)) {
                             if ($method == '__handler') {
                                 $controller[] = '/' . $id;
                             } elseif (substr_count($method, '__') && !substr_count($method, '__async')) {
                                 $new_method = str_replace('__', '', $method);
                                 $controller[] = '/' . $id . '/' . $new_method;
                             }
                         }
                     }
                 }
             } else {
                 $controller = $rmController;
             }
             foreach ($controller as $cntrl) {
                 if (strpos($cntrl, '.php')) {
                     // generate controller URL
                     $cntrl = '/' . locale_path('ru') . strtolower(basename($cntrl, '.php'));
                 }
                 elapsed('Generating HTML snapshot for: ' . $cntrl);
                 // Create curl instance
                 $ch = \curl_init('127.0.0.1' . $cntrl);
                 // Set base request options
                 \curl_setopt_array($ch, array(CURLOPT_VERBOSE => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array('Host: ' . $_SERVER['HTTP_HOST'])));
                 // Add curl too multi request
                 curl_multi_add_handle($mh, $ch);
             }
         }
         // TODO: Create function\module for this
         // Curl multi-request
         $active = null;
         do {
             $mrc = curl_multi_exec($mh, $active);
         } while ($mrc == CURLM_CALL_MULTI_PERFORM);
         while ($active && $mrc == CURLM_OK) {
             if (curl_multi_select($mh) != -1) {
                 do {
                     $mrc = curl_multi_exec($mh, $active);
                 } while ($mrc == CURLM_CALL_MULTI_PERFORM);
             }
         }
         curl_multi_close($mh);
         // Files array
         $files = array();
         // Iterate generated pages
         foreach (\samson\core\File::dir($pages_path, 'html', null, $files, 0) as $f) {
             // Ignore default controller index page as it will be included in this controller
             if (strpos($f, '/index.html') != false) {
                 continue;
             }
             // Read HTML file
             $html = file_get_contents($f);
             // If we have resourcer CSS resource
             if (isset($cssPath[0])) {
                 //$html = str_replace(basename($cssPath, '.css'), 'style', $html);
                 //$html = str_replace('/cache/resourcer/style.css', 'style.css', $html);
                 $html = preg_replace("'<link type=\"text/css\"[^>]*?>'si", '<link type="text/css" rel="stylesheet" href="style.css">', $html);
             }
             // If we have resourcer JS resource
             if (isset($jsPath[0])) {
                 $html = preg_replace("'<script[^>]*?></script>'si", '<script type="text/javascript" src="index.js"></script>', $html);
             }
             // Change path in all img SRC attributes
             if (preg_match_all('/< *img[^>]*src *= *["\']?([^"\']*)/i', $html, $matches)) {
                 if (isset($matches['url'])) {
                     foreach ($matches['url'] as $match) {
                         trace($match . '-' . (__SAMSON_PUBLIC_PATH . ltrim($match, '/')));
                         $html = str_ireplace($match, __SAMSON_PUBLIC_PATH . ltrim($match, '/'), $html);
                     }
                 }
             }
             // Fix images inside modules
             $html = str_replace('<img src="img', '<img src="www/img', $html);
             // Remove relative links
             $html = str_ireplace('<base href="/">', '', $html);
             // Get just file name
             $view_path = ($locale != \samson\core\SamsonLocale::DEF ? $locale . '_' : '') . basename($f);
             // Save HTML file
             file_put_contents($this->output . $view_path, $html);
             // Create index.html record
             $views .= '<a href="' . $view_path . '">' . basename($f) . '</a><br>';
         }
     }
     // Write index file
     file_put_contents($this->output . 'index.html', $views);
     // TODO: Add support to external-internal modules
     // Iterate other resources
     foreach (\samson\core\ResourceMap::get($this->input, false, array(__SAMSON_PUBLIC_PATH . 'out/'))->resources as $type => $files) {
         if (!in_array($type, $this->restricted)) {
             foreach ($files as $f) {
                 $this->copy_resource($f, str_replace($this->input, $this->output, $f));
             }
         }
     }
     $imagesArray = array('png', 'jpg', 'jpeg', 'gif');
     foreach (s()->module_stack as $module) {
         if (isset($module->resourceMap->module[1]) && !substr_count($module->resourceMap->module[1], 'vendor')) {
             foreach ($imagesArray as $format) {
                 if (isset($module->resourceMap->resources[$format]) && sizeof($module->resourceMap->resources[$format])) {
                     foreach ($module->resourceMap->resources[$format] as $file) {
                         $this->copy_resource($file, $this->output . 'www/img/' . basename($file));
                     }
                 }
             }
         }
     }
     // Generate zip file name
     $zip_file = $o_output . 'www.zip';
     elapsed('Creating ZIP file: ' . $zip_file);
     // Create zip archieve
     $zip = new \ZipArchive();
     if ($zip->open($zip_file, \ZipArchive::CREATE) === true) {
         foreach (\samson\core\File::dir($this->output) as $file) {
             $zip->addFile($file, str_replace($this->output, '', $file));
         }
         $zip->close();
     } else {
         elapsed('Cannot create zip file');
     }
 }
示例#25
0
function show_overview()
{
    $unique = 0;
    $sql = "SELECT hash_quick FROM crashes GROUP BY hash_quick;";
    $result = mysql_query($sql);
    if ($result) {
        $unique = mysql_num_rows($result);
        mysql_free_result($result);
    }
    if ($unique > 0) {
        $sql = "SELECT SUM(count) AS total FROM crashes;";
        $result = mysql_query($sql);
        if ($result) {
            $row = mysql_fetch_array($result);
            if ($row) {
                echo "<p class='message-text'>A total of " . htmlentities($row['total'], ENT_QUOTES) . " crashes have been generated, of which " . htmlentities($unique, ENT_QUOTES) . " appear unique.";
                $sql = "SELECT SUM(testcases_per_minute) AS system_tcpm FROM nodes;";
                $result2 = mysql_query($sql);
                if ($result2) {
                    $row = mysql_fetch_array($result2);
                    if ($row) {
                        echo " The system is currently averaging " . htmlentities(intval($row['system_tcpm']), ENT_QUOTES) . " testcases per minute.";
                    }
                    mysql_free_result($result2);
                }
                echo "</p>";
            }
            mysql_free_result($result);
        }
    }
    $sql = "SELECT name, crashes, testcases_per_minute, lastcrash, lastfuzz FROM nodes ORDER BY name ASC;";
    $result = mysql_query($sql);
    if ($result) {
        echo "<ul>";
        if (mysql_num_rows($result) == 0) {
            echo "<li><span class='message-text'>No Grinder nodes are available yet. Go set some up and fuzz something!!!</span></li>";
        }
        while ($row = mysql_fetch_array($result)) {
            // this server may or may not be be +/- N hours from the Nodes
            $diff = intval(GRINDER_TIMEDIFF);
            if ($diff >= 0) {
                $server_time = strtotime('+' . $diff . ' hours');
            } else {
                $server_time = strtotime($diff . ' hours');
            }
            $running = false;
            $lastcrash_period = null;
            $testcases_per_minute = intval($row['testcases_per_minute']);
            $lastcrash = strtotime($row['lastcrash']);
            $lastfuzz = strtotime($row['lastfuzz']);
            if ($lastfuzz) {
                $window = 5;
                if (round(($server_time - $lastfuzz) / 60) < $window + 1) {
                    $running = true;
                }
            }
            if ($lastcrash) {
                $lastcrash_period = elapsed($server_time - $lastcrash);
            }
            if ($running) {
                if ($testcases_per_minute > 0) {
                    $running = "<span class='message-active'>active</span> and averaging " . htmlentities($testcases_per_minute, ENT_QUOTES) . " testcases per minute";
                } else {
                    $running = "<span class='message-active'>active</span>";
                }
            } else {
                $running = "<span class='message-inactive'>inactive</span>";
            }
            echo "<li><span class='message-text'>Node " . htmlentities($row['name'], ENT_QUOTES) . " is currently " . $running . ". " . htmlentities($row['name'], ENT_QUOTES) . " has generated " . htmlentities($row['crashes'], ENT_QUOTES) . " crashes.";
            if (intval($row['crashes']) > 0) {
                if ($lastcrash_period) {
                    echo " The last crash was " . htmlentities($lastcrash_period, ENT_QUOTES) . " ago.";
                }
            }
            echo "</span></li><br/>";
        }
        echo "</ul>";
        mysql_free_result($result);
    }
}
 /**
  * @param Model $o
  * @return Boolean
  */
 public static function cacheExpired($o)
 {
     $mod_time = isset($o::$mod_time) ? $o::$mod_time : null;
     if (!$mod_time) {
         return false;
     }
     if (!$o->_cached_time) {
         return true;
     }
     $is_expired = (bool) (strtotime($o->_cached_time) <= strtotime($mod_time));
     elapsed('cacheExpired:' . var_export($is_expired, true));
     return $is_expired;
 }
示例#27
0
文件: CMS.php 项目: samsonos/cms_api
 /** Removing old tables */
 public function migrate_31_to_32()
 {
     elapsed('Removing `unitable` table');
     db()->query('DROP TABLE IF EXISTS ' . dbMySQLConnector::$prefix . 'unitable');
     elapsed('Removing `scmstable` table');
     db()->query('DROP TABLE IF EXISTS ' . dbMySQLConnector::$prefix . 'scmstable');
 }
示例#28
0
 public function checkPath($qs, $prefix = null)
 {
     # reset the found settings for this object
     $this->cleanSettings();
     // remove falsy folders (but not 0)
     $qs = array_filter($qs, function ($a) {
         if ($a == '0') {
             return true;
         }
         if (!$a) {
             return false;
         }
         return true;
     });
     $this->qs = $qs;
     $this->prefix = $prefix;
     for ($i = $i + 1; $i <= count($qs); $i++) {
         $path_arr = array_slice($qs, 0, $i);
         $slug = $path_arr[$i - 1];
         $path = implode('/', $path_arr);
         if ($path && $prefix) {
             $path = '/' . $path;
         }
         $settings_file = $this->ft($prefix, $path, $slug, 'settings');
         $script_file = $this->ft($prefix, $path, $slug, 'script');
         $this->includePreSettings();
         $this->includeToSettings($settings_file);
         $this->appendScript($script_file);
         $check = array(sprintf('%s%s.php', $prefix, $path) => true, sprintf('%s%s/%s.php', $prefix, $path, $slug) => true, $this->ft($prefix, $path, $slug, 'profile') => 'profile', $this->ft($prefix, $path, $slug, 'listing') => true);
         foreach ($this->codebase_paths as $codebase_path) {
             $file = '';
             $get_tmp = function ($f) use($codebase_path) {
                 return $codebase_path . $f;
             };
             foreach ($check as $file => $c) {
                 $tmp = $get_tmp($file);
                 if (!is_file($tmp)) {
                     continue;
                 }
                 if ($c === 'profile') {
                     if ($this->checkProfile($qs[$i + 1], $i, $file, $tmp)) {
                         break 2;
                     }
                 } else {
                     $this->addToPageAndPath($file, $tmp, $i);
                     break 2;
                 }
             }
             $file = $prefix . $path;
             $tmp = $get_tmp($file);
             if ($path && is_dir($tmp)) {
                 $this->page[$i] = 'directory';
             }
         }
         if ($this->page[$i]) {
             $this->includePostSettings();
             continue;
         }
         if (!$this->db) {
             continue;
         }
         $path_arr = array_slice($qs, 0, $i - 1);
         $path = implode('/', $path_arr);
         if ($path && $prefix) {
             $path = '/' . $path;
         }
         $matches = array();
         foreach ($this->codebase_paths as $codebase_path) {
             $scandir = $codebase_path . $prefix . $path;
             if (!is_dir($scandir)) {
                 continue;
             }
             foreach (scandir($scandir) as $filename) {
                 if (substr($filename, 0, 1) != '_' || strlen($filename) <= 6) {
                     continue;
                 }
                 if (substr($filename, -1) != '_') {
                     continue;
                 }
                 if (!is_dir($scandir . '/' . $filename)) {
                     continue;
                 }
                 $matches[substr($filename, 1, -1)] = $codebase_path;
             }
         }
         if (!$matches) {
             continue;
         }
         foreach ($matches as $field => $codebase_path) {
             $folder = '_' . $field . '_';
             $table = substr($field, 0, strpos($field, '.'));
             $settings_file = $this->dft($prefix, $path, $folder, 'settings');
             $script_file = $this->dft($prefix, $path, $folder, 'script');
             $this->includePreSettings();
             $this->includeToSettings($settings_file);
             $lookup_id = null;
             if (!$this->settings['database_folder']['numeric_slug'] || is_numeric($slug)) {
                 $sql = "SELECT id FROM {$table} WHERE active = 1 and {$field} = '{$slug}'";
                 if ($this->settings['database_folder']['where']) {
                     $sql .= ' and ' . $this->settings['database_folder']['where'];
                 }
                 \elapsed($sql);
                 $r = sql($sql);
                 if (!$r->EOF) {
                     $lookup_id = $r->Fields('id');
                 }
                 $r = null;
             }
             // clear database folder settings
             $this->settings['database_folder'] = null;
             if ($lookup_id === null) {
                 continue;
             }
             $this->includePostSettings();
             $qs[$i] = $folder;
             $lookup_field_id = $table . '_id';
             ${$lookup_field_id} = $lookup_id;
             $this->vars[$lookup_field_id] = $lookup_id;
             $lookup_slug = str_replace('.', '_', $field);
             ${$lookup_slug} = $slug;
             $this->vars[$lookup_slug] = $slug;
             $this->appendScript($script_file);
             $get_tmp = function ($f = null) use($codebase_path) {
                 return $codebase_path . $f;
             };
             $check = array(sprintf('%s%s/%s/%s.php', $prefix, $path, $folder, $folder) => true, $this->dft($prefix, $path, $folder, 'profile') => 'profile', $this->dft($prefix, $path, $folder, 'listing') => true);
             foreach ($check as $file => $c) {
                 $tmp = $get_tmp($file);
                 if (!is_file($tmp)) {
                     continue;
                 }
                 if ($c === 'profile') {
                     if ($this->checkProfile($qs[$i + 1], $i, $file, $tmp)) {
                         break 2;
                     }
                 } else {
                     $this->addToPageAndPath($file, $tmp, $i);
                     break 2;
                 }
             }
             $file = sprintf('%s%s/%s', $prefix, $path, $folder);
             $tmp = $get_tmp();
             if (is_dir($tmp)) {
                 $this->page[$i] = 'directory';
             }
         }
         if ($this->page[$i]) {
             continue;
         }
     }
 }