<?
/*
This file keeps the library functions offered
and used by PHP-PAPA
===========================================================
FileName : papa/core.php
License : GNU/LGPL
Project : PHP-PAPA
Type : PHP Framework
Class Name : !!!
Version : 1.0
===========================================================
*/
/*************************************************************************
* Global variables
*************************************************************************/
$__PAPA__LINKS__ = array();
$__PAPA__TITLE = '';
function papa_title($title=''){
global $__PAPA__TITLE;
global $papa_config;
if(empty($title)){
return $papa_config["application"]["name"] . ' ' . $__PAPA__TITLE;
}else{
$__PAPA__TITLE = $title;
}
}
function papa_link_all(){
global $__PAPA__LINKS__;
foreach($__PAPA__LINKS__ as $link){
echo $link;
}
}
function papa_add_link($link,$atfirst=false){
global $__PAPA__LINKS__;
if($atfirst){
array_unshift($__PAPA__LINKS__,$link);;
}else{
array_push($__PAPA__LINKS__,$link);
}
}
function papa_sanitize($input,$link){
if(is_array($input)){
foreach($input as $k=>$i){
$output[$k]=papa_sanitize($i,$link);
}
}
else{
if(get_magic_quotes_gpc()){
$input=stripslashes($input);
}
$output=mysql_real_escape_string($input);
}
return $output;
}
function papa_clean( $value, $allow = '' ){
$value = papa_sanitize( $value, NULL );
if( empty($allow) ){
$allow = '<p><a><b><i><div><span><img><u><i><br><hr><br/><hr/>';
}
$value = strip_tags($value,$allow);
return $value;
}
/*************************************************************************
* Load the core files,
*************************************************************************/
//$papa_base_dir = $_SERVER['DOCUMENT_ROOT'].substr($_SERVER['SCRIPT_NAME'],0,strrpos($_SERVER['SCRIPT_NAME'],'/'));
include $papa_base_dir . '/papa/DAL.php';
include $papa_base_dir . '/papa/MAL.php';
include $papa_base_dir . '/papa/ActiveRelationalRecord.php';
include $papa_base_dir . '/papa/IPolice.php';
include($papa_base_dir . '/papa/ControllerSession.php');
include($papa_base_dir . '/papa/ControllerPost.php');
include($papa_base_dir . '/papa/ControllerGet.php');
include($papa_base_dir . '/papa/ControllerCookie.php');
//include($papa_base_dir . '/papa/Component.php');
include($papa_base_dir . '/papa/Controller.php');
include($papa_base_dir . '/papa/PapaSession.php');
include($papa_base_dir . '/ssi.php');
/*----------------------------------------------------------------------*/
/**
* Get the translation
*
* TODO: make it accpet formatted string and use sprintf.
*/
function __($key){
global $__PAPA_LANG__;
if(empty($__PAPA_LANG__[strtolower($key)])){
return $key;
}else{
return $__PAPA_LANG__[strtolower($key)];
}
}
/*----------------------------------------------------------------------*/
/*************************************************************************
* Functions related to debug
************************************************************************/
/**
* saves the debug messages
*/
if(! isset($_SESSION['__PAPA_DEBUG__'])){
$_SESSION['__PAPA_DEBUG__'] = array();
}
$__PAPA_DEBUG__ = $_SESSION['__PAPA_DEBUG__'];
/**
* sets the debug more
*/
function papa_debug_on(){
global $__PAPA_DEBUG__ON__;
$__PAPA_DEBUG__ON__ = true;
}
/**
* unsets the debug more
*/
function papa_debug_off(){
global $__PAPA_DEBUG__ON__;
$__PAPA_DEBUG__ON__ = false;
}
/**
* checks if the debug mode is on
*/
function papa_is_debug_on(){
global $__PAPA_DEBUG__ON__;
return $__PAPA_DEBUG__ON__;
}
/**
* Logs a debug string. the message is added into the debug
* array
*
* TODO: make it accpet formatted string and use sprintf.
*/
function __log($msg){
global $__PAPA_DEBUG__;
array_push($__PAPA_DEBUG__, $msg.'<br>');
}
/*----------------------------------------------------------------------*/
/*************************************************************************
* Functions related to session handling
************************************************************************/
function papa_session_get($key){
$ret = $_SESSION['__PAPA__'.$key];
return $ret;
}
function papa_session_set($key,$val){
$_SESSION['__PAPA__'.$key] = $val;
}
/*----------------------------------------------------------------------*/
/*************************************************************************
* Functions related to load view/classes etc
************************************************************************/
/**
* Loads a view in a cascading manner
*
* First it checks if a view is present under the current locale folder.
* if not then loads from the view folder.
*
* For example, say current local is 'bn', Requested view is 'profile/inbox'.
* papa first tries to load '/views/_bn/profile/inbox'.
* If failed, it loads '/views/profile/inbox'.
*
* @param $view The view file name without extension
* @param array $params Associated array
* @param $locale override current locale with this.
*/
function papa_load_view($view,array $params=array(),$locale=''){
global $__PAPA_LOCALE_;
if(empty($locale)){ // local is not passed
$locale = $__PAPA_LOCALE_; // use current locale
}
extract($params);
if(file_exists('views/_'.$locale.'/'.$view.'.php')){
include('views/_'.$locale.'/'.$view.'.php');
}else{
include('views/'.$view.'.php');
}
}
function papa_get_current_theme_css($css='style'){
return papa_get_base_url(ControllerCookie).'/theme/'.papa_get_current_theme().'/css/'.$css.'.css';
}
function papa_use_current_theme_css($css='style'){
print("\n");
echo '<link href="'.papa_theme_base().'/css/'.$css.'.css" rel="stylesheet" type="text/css" />';
print("\n");
}
function papa_get_current_theme(){
return empty($_SESSION['__PAPA__theme'])?'default' : $_SESSION['__PAPA__theme'];
}
// set current theme
function papa_set_current_theme($theme){
if( ! is_dir( getcwd(). 'theme'.'/'.$theme ) ){
$_SESSION['__PAPA__theme']=$theme;
}else{
die($theme.' does not exists!');
}
}
function papa_set_locale($locale){
$_SESSION['__PAPA__locale__'] = $locale;
$last_url = papa_session_get('last_url');
header('location:'.$last_url);
}
function papa_get_locale(){
return $_SESSION['__PAPA__locale__'];
}
/**
* Redirect to the last page visited
* if the last page was not saved, redirect to home page
*
* @param $alt Alternate url if last page was not saved
*/
function papa_goto_lasturl($alt = ''){
$last_url = papa_session_get('last_url');
if( empty($last_url) ){
$last_url = $alt;
}
if( empty( $last_url )){
$last_url = papa_get_base_url();
}else{
papa_set_lasturl('');
}
header('location:'.$last_url);
}
function papa_get_themes(){
$themes = array();
$curtheme = papa_get_current_theme();
if ($handle = opendir('theme/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && $file[0]!= '.') {
if(is_dir('theme/'.$file)){
$themes[$file] = $file==$curtheme ? 'selected' : '';
}
}
}
closedir($handle);
}
if($htmlselect)$themes.='</select>';
return $themes;
}
function __autoload($class){
$class = str_replace('.','/',$class);
require_once 'classes/'.$class.'.php';
}
function papa_use($class){
global $papa_base_dir;
require_once $papa_base_dir.'/classes/'.str_replace('.','/',$class).'.php';
}
function papa_load($class,array $args=array()){
$papa_base_dir = $_SERVER['DOCUMENT_ROOT'].substr($_SERVER['SCRIPT_NAME'],0,strrpos($_SERVER['SCRIPT_NAME'],'/'));
$cls = str_replace('.','/',$class);
require_once($papa_base_dir.'/classes/'.$cls.'.php');
$arr = explode('.',$class);
$ref = new ReflectionClass($arr[count($arr)-1]);
return $ref->newInstanceArgs($args);
}
function papa_redirect($url,$addPrefix = true){
if($addPrefix){
header('Location:'.papa_get_base_url().'/'.$url);
}else{
header('Location:'.'/'.$url);
}
}
function papa_refresh($url,$time='2'){
header("Refresh:$time;url=".papa_url($url));
}
function papa_url($url){
global $papa_base_url;
return $papa_base_url.'/'.$url.'.html';
}
function papa_theme_base($relativePath = false){
global $papa_base_dir;
if($relativePath == true){
return $papa_base_dir . '/theme/' . papa_get_current_theme();
}else{
return papa_get_base_url() . '/theme/' . papa_get_current_theme();
}
}
////////////////helpers////////////////////////
function papa_get_args(){
global $req;
return $req;
}
function papa_get_app_name(){
global $papa_app_name;
return $papa_app_name;
}
function papa_get_base_url(){
global $papa_base_url;
return $papa_base_url;
}
function papa_get_current_controller_name(){
global $controllerPath;
return $controllerPath;
}
function papa_get_current_method_name(){
global $method;
return $method;
}
/**
* This function changes the theme with the one passed.
* After setting the new theme, it also redirects the browser
* to the last from where it was originally called.
*
* This function may not be directly used, it is used by the
* <code>papa_theme_combo</code> function;
*
* @param $theme The new theme name
*/
function papa_change_theme($theme){
papa_set_current_theme($theme);
papa_goto_lasturl();
}
/**
* This function shows the available themes in a select combo/dropdown.
* All folder available under the theme folder are treated as a separate
* theme. Any folder started with a '.'(dot) are omitted.
*
* Use it like:
* <code>echo papa_theme_combo();</code>
*
* @param $id Set the id of the select tag
* @param $class Set the class of the select tag
* @return The select html code in a string.
*/
function papa_theme_combo($id='papablog_themes',$class='papablog_themes'){
global $papa_base_path;
papa_set_lasturl();
$themes = papa_get_themes();
$out = '<select id="'.$id.'" class="'.$class.'" onchange="var theme = this.options[this.selectedIndex].value;window.location=\''.papa_get_base_url().'/_papa/papa_change_theme/\'+theme">';
foreach($themes as $theme=>$selected){
$out.='<option value="'.$theme.'" '.$selected.'>'.$theme.'</option>';
}
$out.='</select>';
return $out;
}
function papa_set_lasturl($url=''){
global $papa_base_path;
global $papa_base_url;
if(mb_strlen($url, 'UTF-8' ) < 1 ){
$url = substr($_SERVER["REQUEST_URI"],mb_strlen($papa_base_path, 'UTF-8' )+1);
$url = $papa_base_url . '/' . $url;
}
papa_session_set('last_url',$url);
}
/**
* Link a js file
*
* @param $filename JS filename without extension
* @param $dumpContent if true, without linking dubmp the content in a script tag block.
* might be used in FB
*/
function papa_js($filename,$dumpContent = false){
if(!$dumpContent){
papa_add_link('<script src="'.papa_get_base_url().'/js/'.$filename.'.js"></script>');
}else{
echo '<script>';
echo 'dsfdsf';
echo '</script>';
die('../js/'.$filename.'.js');
}
}
/**
* Link a js file for a module
*
* @param $filename JS filename without extension
* @param $dumpContent if true, without linking dubmp the content in a script tag block.
* might be used in FB
*/
function papa_mod_js($module,$filename,$dumpContent = false){
if( empty($filename) ){
$filename = $module;
}
if(!$dumpContent){
papa_add_link('<script src="'.papa_get_base_url().'/modules/'.$module.'/js/'.$filename.'.js"></script>');
}else{
echo '<script>';
echo file_get_contents(getcwd().'/modules/'.$module.'/js/'.$filename.'.js');
echo '</script>';
}
}
function papa_mod_css($module,$filename,$dumpContent = true){
if( empty($filename) ){
$filename = $module;
}
if(!$dumpContent){
$bu = papa_get_base_url();
papa_add_link('<link href="'.papa_get_base_url().'/modules/'.$module.'/css/'.$filename.'.css" rel="stylesheet" type="text/css" />');
}else{
echo '<style type="text/css">';
echo file_get_contents(getcwd().'/modules/'.$module.'/css/'.$filename.'.css');
echo '</style>';
}
}
function papa_load_module($module){
papa_mod_css($module,$module,false);
papa_mod_js($module,$module,false);
require_once getcwd().'/modules/'.$module.'/'.$module.'.php';
return new $module();
}
/*
function papa_component($comp,$args=array()){
global $papa_base_dir;
$comp = str_replace('.','/',$comp);
if(!is_array($args)){
$tmp = papa_get_args();
array_shift($tmp);
$len = count($tmp);
$args = array();
for($i=0;$i < $len; $i=$i+2){
$args[$tmp[$i]] = $tmp[$i+1];
}
}
extract($args);
if(file_exists(papa_theme_base(true).'/components/' . $comp . '/index.php')){
include( papa_theme_base(true).'/components/' . $comp . '/index.php');
}else{
include( $papa_base_dir . '/components/' . $comp . 'index.php');
}
}*/
function papa_component($comp,$args=array(),$file='index'){
global $papa_base_dir;
$comp = str_replace('.','/',$comp);
if(!is_array($args)){
$tmp = papa_get_args();
array_shift($tmp);
$len = count($tmp);
$args = array();
for($i=0;$i < $len; $i=$i+2){
$args[$tmp[$i]] = $tmp[$i+1];
}
}
extract($args);
if(file_exists(papa_theme_base(true).'/components/' . $comp . '/' . $file . '.php')){
include( papa_theme_base(true).'/components/' . $comp . '/' . $file . '.php');
}else{
include( $papa_base_dir . '/components/' . $comp . '/' . $file .'.php');
}
}
function papa_component_url($comp,$file){
global $papa_base_dir;
$comp = str_replace('.','/',$comp);
if(!is_array($args)){
$tmp = papa_get_args();
array_shift($tmp);
$len = count($tmp);
$args = array();
for($i=0;$i < $len; $i=$i+2){
$args[$tmp[$i]] = $tmp[$i+1];
}
}
extract($args);
if(file_exists(papa_theme_base(true).'/components/' . $comp . '/' . $file)){
return( papa_theme_base().'/components/' . $comp . '/' . $file);
}else{
return( papa_get_base_url() . '/components/' . $comp . '/' . $file);
}
}
function papa_show_app_old($applet,$params){
global $papa_base_dir;
global $papa_config;
ob_start();
include($papa_base_dir . '/applets/' . $applet . '/index.php');
$content = ob_get_contents();
ob_end_clean();
include($papa_base_dir . '/theme/'. papa_get_current_theme() . '/layouts/applet.php' );
}
function papa_show_app($app){
global $papa_base_dir;
global $papa_config;
global $path;
global $papa_base_path;
$path = '/applets' . substr($path,(strlen($papa_base_path)+4));
$params = '';
//extract the GET param
if(strpos($_SERVER["REQUEST_URI"],'?')!==false){
$params = '?' . substr($_SERVER["REQUEST_URI"],strpos($_SERVER["REQUEST_URI"],'?')+1);
}
$ch = curl_init();
// use the current session
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, -1); // To suppress echoing the output
if($_SERVER['REQUEST_METHOD']=='POST'){
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$_POST);
curl_setopt($ch, CURLOPT_URL, papa_get_base_url() .$path . $params) ;
$content = curl_exec($ch);
if(curl_errno($ch))
{
die('erro'.$content);
}
}else{
// Curl is used to check if the content is dynamically generated
//binary files like images.
//
//History:
// While using SMF as an applet I found the captcha is not coming.
//*
curl_setopt($ch, CURLOPT_URL, papa_get_base_url() .$path . $params);
curl_setopt($ch, CURLOPT_HEADER, 0);
// Execute
$content = curl_exec($ch);
// Check if any error occured
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
// shadow Urls like http://localhost/papa/app/smf.html
if(strpos($info['content_type'],'text')===0){
//$content = file_get_contents(papa_get_base_url() .$path . $params );
}else{//So its a binary file.
header("Content-Type: " . $info['content_type']);
curl_close($ch); // free the resource
die($content);
//die(file_get_contents(papa_get_base_url() .$path . $params . '&PHPSESSID='.session_id() ));
}
}else{//what to do? Any idea?
}
}
// Close handle
curl_close($ch);//*/
$primaryurl = $papa_config['application']['base_path'] . '/applets/' . $app;
$secondaryurl =$papa_config['application']['base_path'] . '/app/' . $app;
$pattern = "~{$primaryurl}/([\d\S\/]+)~";
//Don't uncomment it now, it will be used on future version.
//$content = preg_replace($pattern,"{$secondaryurl}/$1",$content);
$content = str_replace(array("<a href=\"{$primaryurl}"
,"<form action=\"{$primaryurl}")
,array("<a href=\"{$secondaryurl}"
,"<form action=\"{$secondaryurl}"),$content);
$primaryurl = papa_get_base_url() . '/applets/' . $app;
$secondaryurl =papa_get_base_url() . '/app/' . $app;
//echo($primaryurl);
$pattern = "~{$primaryurl}/([\d\S\/]+)~";
$content = str_replace(array("<a href=\"{$primaryurl}"
,"<form action=\"{$primaryurl}"
,"<a href='{$primaryurl}"
,"href=\".")
,array("<a href=\"{$secondaryurl}"
,"<form action=\"{$secondaryurl}"
,"<a href='{$secondaryurl}"
,"href=\"".papa_get_base_url() . '/applets/'.$app,),$content);
if(file_exists($papa_base_dir . '/applets/' . $app . '/layout.php')){
include($papa_base_dir . '/applets/' . $app . '/layout.php');
}else{
include($papa_base_dir . '/theme/'. papa_get_current_theme() . '/layouts/applet.php' );
}
}
function papa_404($msg=''){
echo '<div style="margin: auto auto;border:0px solid red;min-height:200px;width:100%;">Page not found</div>';
}
function papa_is_posted(){
return ($_SERVER['REQUEST_METHOD'] == 'POST');
}
function papa_make_path($path){
$path = ereg_replace( '/+', "/", $path );
if( substr( $path, -1 ) == '/' ){ // Remove any trailing slash
$path = substr( $path, 0, -1 );
}
if( $path{0} == '/' ){ // Remove any front slash
$path = substr( $path, 1 );
}
$pattern = array('/[\'"]/','/[^a-zA-Z0-9_\/]+/');
$replace = array('','-');
$path = preg_replace($pattern,$replace,strip_tags(strtolower($path)));
return $path;
}
function papa_get_polices($path){
global $papa_config;
$polices = array();
$max=0;
do{
foreach($papa_config['police'] as $key=>$val){
if($path==$key){
$polices[]=$val;
//echo 'got it';
break 2;
}
}
$path = substr($path,0,strrpos($path,'/'));
}while(strlen($path)>0);
$polices = @array_values($polices[0]);
return $polices;
}
//papa 1.1
function papa_get_view($view,$locale){
global $controllerPath;
$path = '/'.$controllerPath ;
$path_prefix = 'theme/' . papa_get_current_theme().'/views';
$applet=false;
do{
if( file_exists($path_prefix .$path .'/'. $view.'.php' )){
$applet = $path_prefix . $path .'/'. $view .'.php';
//die('here');
break;
}
$path = '/' . substr($path,0,strrpos($path,'/'));
}while(strlen($path)>0);
if($applet!==false){
//check if translation is there
if(file_exists('theme/' . papa_get_current_theme().'/views/_'.$locale.$path.'/'.$view)){
$applet = 'theme/' . papa_get_current_theme().'/views/_'.$locale.$path.'/'.$view;
}
return $applet;
}
// view not found, check under fefault theme
$path = '/'.$controllerPath ;
$path_prefix = 'theme/default/views';
$applet=false;
do{
if( file_exists($path_prefix .$path .'/'. $view.'.php' )){
$applet = $path_prefix . $path .'/'. $view .'.php';
//die('here');
break;
}
$path = '/' . substr($path,0,strrpos($path,'/'));
}while(strlen($path)>0);
if($applet!==false){
//check if translation is there
if(file_exists('theme/default/views/_'.$locale.$path.'/'.$view)){
$applet = 'theme/default/views/_'.$locale.$path.'/'.$view;
}
return $applet;
}
return false;
}
//////////////end helper////////////////////////
//////////////////////////////////////////////////////////////
?> |