Ejemplo n.º 1
0
 protected function fetch($pTplName, &$pTplSource, &$pTplTime)
 {
     global $gBitLanguage, $gBitThemes, $gBitSmarty;
     $ret = '';
     // We're gonna run our own cache mechanism for user_modules
     // the cache is here to avoid calls to consumming queries,
     // each module is different for each language because of the strings
     $cacheDir = TEMP_PKG_PATH . 'modules/cache/';
     if (!is_dir($cacheDir)) {
         mkdir_p($cacheDir);
     }
     list($package, $template) = explode('/', $pTplName);
     $cacheFile = $cacheDir . '_custom.' . $gBitLanguage->mLanguage . '.' . $template . '.tpl.cache';
     if (!empty($r["cache_time"]) && file_exists($cacheFile) && !($gBitSystem->getUTCTime() - filemtime($cacheFile) > $r["cache_time"])) {
         $pTplSource = file_get_contents($cacheFile);
     } else {
         global $moduleParams;
         if ($moduleParams = $gBitThemes->getCustomModule($template)) {
             $gBitSmarty->assign_by_ref('moduleParams', $moduleParams);
             $pTplSource = $gBitSmarty->fetch('bitpackage:themes/custom_module.tpl');
             // write to chache file
             $fp = fopen($cacheFile, "w+");
             fwrite($fp, $data, strlen($data));
             fclose($fp);
         }
     }
     $pTplTime = filemtime($cacheFile);
 }
Ejemplo n.º 2
0
 function __get_local_file($local_id, $test_dir = false)
 {
     $path = HOME_DIR . '/upload/' . $local_id;
     if (!is_dir($dir = dirname($path))) {
         mkdir_p($dir, 0777);
     }
     return $path;
 }
Ejemplo n.º 3
0
 /**
  * Initialisation of this class
  */
 function Nexus($pMenuId = NULL)
 {
     parent::__construct();
     $this->mMenuId = $pMenuId;
     // if the cache folder doesn't exist yet, create it
     if (!is_dir(TEMP_PKG_PATH . NEXUS_PKG_NAME . '/modules')) {
         mkdir_p(TEMP_PKG_PATH . NEXUS_PKG_NAME . '/modules');
     }
 }
Ejemplo n.º 4
0
 function _path($key, $mkdir = false)
 {
     $dir = HOME_DIR . '/cache/' . $key[0] . $key[1];
     if ($mkdir) {
         if (!mkdir_p($dir)) {
             return false;
         }
     }
     return $dir . '/' . substr($key, 2);
 }
Ejemplo n.º 5
0
 function upgrade_gimages()
 {
     $this->title = '商品图片';
     $aGoods = $this->db->select('SELECT goods_id,type_id, image_default, image_file FROM sdb_goods ORDER BY goods_id ASC LIMIT ' . ($this->step - 1) * 100 . ', 100');
     if (empty($aGoods)) {
         $this->updateMsg = update_message('商品图片升级成功');
         return 'finish';
     }
     foreach ($aGoods as $gv) {
         $hasG = $this->db->selectrow('SELECT COUNT(gimage_id) AS c FROM sdb_gimages WHERE goods_id = ' . $gv['goods_id']);
         if ($hasG['c']) {
             continue;
         }
         foreach (explode(',', $gv['image_file']) as $iv) {
             $iv = trim($iv);
             $gimagesData['is_remote'] = 'false';
             //                $gimagesData['source'] = $iv;
             $gimagesData['goods_id'] = $gv['goods_id'];
             $defPicSrc = '';
             if (substr($iv, 0, 4) == 'http') {
                 $gimagesData['is_remote'] = 'true';
                 $defPicSrc = 'N';
                 foreach (array('small', 'big', 'thumbnail') as $iType) {
                     $gimagesData[$iType] = $iv;
                 }
             } else {
                 $oldImgSrc = explode('|', $iv);
                 $defPicSrc = $oldImgSrc[0];
                 $extName = strrchr($defPicSrc, '.');
                 mkdir_p(dirname(HOME_DIR . '/upload/' . $defPicSrc));
                 copy(BASE_DIR . $defPicSrc, HOME_DIR . '/upload/' . $defPicSrc);
                 unlink(BASE_DIR . $defPicSrc);
                 chmod(HOME_DIR . '/upload/' . $defPicSrc, 0777);
                 foreach (array('small', 'big', 'thumbnail') as $iType) {
                     $gimagesData[$iType] = str_replace($extName, '_' . $iType . $extName, $iv);
                 }
             }
             $this->db->exec('INSERT INTO sdb_gimages ( 
                 goods_id , is_remote , source , src_size_width , src_size_height , small , big , thumbnail , up_time 
             ) VALUES (
                 ' . $gv['goods_id'] . ' , "' . $gimagesData['is_remote'] . '" , "' . $defPicSrc . '" , 100 , 100 , "' . $gimagesData['small'] . '" , "' . $gimagesData['big'] . '" , "' . $gimagesData['thumbnail'] . '" , ' . time() . '
             )');
             $lastId = $this->db->lastInsertId();
             if ($iv == trim($gv['image_default'])) {
                 if (!$this->db->exec('UPDATE sdb_goods SET image_default = "' . $lastId . '" , small_pic = "' . $gimagesData['small'] . '", big_pic = "' . $gimagesData['big'] . '" WHERE goods_id = ' . $gv['goods_id'])) {
                     $this->updateMsg = update_message('商品图片升级失败', E_WARNING);
                     return 'error';
                 }
             }
         }
     }
     return 'continue';
 }
Ejemplo n.º 6
0
 function dazuiLog()
 {
     $system =& $GLOBALS['system'];
     $map = array('date' => date('Y-m-d'), 'worker' => 'shop', 'controller' => isset($system->request['action']['controller']) ? $system->request['action']['controller'] : '-', 'method' => isset($system->request['action']['method']) ? $system->request['action']['method'] : '-', 'query' => isset($system->request['query']) ? $system->request['query'] : '-', 'ip' => remote_addr());
     foreach ($map as $k => $v) {
         $find[] = '/\\{' . $k . '\\}/i';
     }
     $this->file = preg_replace($find, $map, LOG_FILE);
     if (!is_dir($dir = dirname($this->file))) {
         mkdir_p($dir);
     }
     $this->logStr = create_function('$e', 'return "' . preg_replace(array_merge($find, array('/\\{time\\}/i', '/\\{gmt\\}/i', '/\\{code\\}/i', '/\\{msg\\}/i')), array_merge($map, array('".mydate(\'h:i:s\')."', '[".mydate(\'r\')."]', '".str_pad($e[\'code\'],4,0, STR_PAD_LEFT)."', '".str_replace("\\n",\'\\n\',$e[\'msg\'])."')), str_replace('"', '\\"', LOG_FORMAT)) . '";');
 }
Ejemplo n.º 7
0
function data_graphviz($data, $params)
{
    $data = trim($data);
    $data = html_entity_decode($data);
    $storageurl = STORAGE_PKG_URL . 'GraphViz/';
    $storagepath = STORAGE_PKG_PATH . 'GraphViz/';
    $temppath = TEMP_PKG_PATH . 'GraphViz/';
    if (!is_dir($temppath)) {
        mkdir_p($temppath);
    }
    if (!is_dir($storagepath)) {
        mkdir_p($storagepath);
    }
    $file = md5($data);
    $dotFile = $temppath . $file . '.dot';
    $pngFile = $storagepath . $file . '.png';
    $pngURL = $storageurl . $file . '.png';
    if (!file_exists($pngFile)) {
        if (@(include_once 'PEAR.php')) {
            if (@(include_once 'Image/GraphViz.php')) {
                $graph = new Image_GraphViz();
                $error = '<div class=error>' . tra("Unable to write temporary file. Please check your server configuration.") . '</div>';
                if (!($fp = fopen($dotFile, 'w'))) {
                    return $error;
                }
                if (fwrite($fp, $data) === false) {
                    return $error;
                }
                fclose($fp);
                $graph->renderDotFile($dotFile, $pngFile, 'png');
                // No need to keep this lying around
                unlink($dotFile);
                // If it still isn't there....
                if (!file_exists($pngFile)) {
                    return '<div class=error>' . tra("Unable to generate graphviz image file. Please check your data.") . '</div>';
                }
            } else {
                return "<div class=error>" . tra("The Image_Graphviz pear plugin is not installed. Install with `pear install Image_Graphviz`.") . "</div>";
            }
        } else {
            return "<div class=error>" . tra("PEAR and the Image_Graphviz pear plugin are not installed.") . "</div>";
        }
    }
    return "<img src=\"{$pngURL}\"/> ";
}
Ejemplo n.º 8
0
 function _get_ident($file, $type, $addons, &$url, &$path)
 {
     $addons = implode('-', $addons);
     $dir = '/' . $type . '/' . date('Ymd') . '/';
     $uri = $dir . substr(md5(($addons ? $addons : $file) . microtime()), 0, 16) . ext_name(basename($addons ? $addons : $file));
     $path = MEDIA_DIR . $uri;
     $url = 'images' . $uri;
     if (file_exists($path) && !unlink($path)) {
         return false;
     }
     $dir = dirname($path);
     if (!is_dir($dir)) {
         if (!mkdir_p($dir)) {
             return false;
         }
     }
     return $uri;
 }
Ejemplo n.º 9
0
function mkdir_p($target)
{
    // from php.net/mkdir user contributed notes
    if (file_exists($target)) {
        if (!is_dir($target)) {
            return false;
        } else {
            return true;
        }
    }
    // Attempting to create the directory may clutter up our display.
    if (@mkdir($target)) {
        return true;
    }
    // If the above failed, attempt to create the parent node, then try again.
    if (mkdir_p(dirname($target))) {
        return mkdir_p($target);
    }
    return false;
}
Ejemplo n.º 10
0
 protected function copy_manifest()
 {
     foreach ($this->manifest() as $target => $source) {
         if ($source === true) {
             if ($target[strlen($target) - 1] == '/') {
                 mkdir_p($target);
             } else {
                 mkdir_p(dirname($target));
                 touch($target);
             }
         } else {
             $target = ZING_ROOT . '/' . ltrim($target, '/');
             mkdir_p(dirname($target));
             if ($this->is_file_templated($source, $target)) {
                 file_put_contents($target, $this->render_template($source));
             } else {
                 file_put_contents($target, file_get_contents($source));
             }
         }
     }
 }
Ejemplo n.º 11
0
function mkdir_p($target)
{
    //creates a new directory
    //Returns 1 for success
    //        2 for "directory/file by that name exists
    //        0 for other errors
    if (file_exists($target) || is_dir($target)) {
        return 2;
    }
    if (mkdir($target, 0777)) {
        return 1;
    }
    if (mkdir_p(substr($target, 0, strrpos($target, '/'))) == 1) {
        if (mkdir_p($target) == 1) {
            return 1;
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}
Ejemplo n.º 12
0
function mkdir_p($target)
{
    // from php.net/mkdir user contributed notes
    $target = str_replace('//', '/', $target);
    if (file_exists($target)) {
        return @is_dir($target);
    }
    // Attempting to create the directory may clutter up our display.
    if (@mkdir($target)) {
        $stat = @stat(dirname($target));
        $dir_perms = 0777;
        // Get the permission bits.
        @chmod($target, $dir_perms);
        return true;
    } elseif (is_dir(dirname($target))) {
        return false;
    }
    // If the above failed, attempt to create the parent node, then try again.
    if ($target != '/' && mkdir_p(dirname($target))) {
        return mkdir_p($target);
    }
    return false;
}
Ejemplo n.º 13
0
/**
 * moduleinc 
 * 
 * Usage: add to the body of any .tpl file
 * Example: {inlinemodule file="_custom:custom/my_custom_module" cache_time=600}
 *
 * Note: currently only supports custom modules generated in themes package, 
 * could support any module with more work
 *
 * @param array $pParams 
 * @param string $pParams['module_rsrc'] the full name of the template, example: _custom:custom/my_custom_module 
 * @param integer $pParams['cache_time'] seconds the template will be cached
 */
function smarty_function_moduleinc($pParams, &$gBitSmarty)
{
    global $gBitSystem, $gBitThemes;
    // go through some hassle here in consideration of a future day when this handles any module
    list($package, $template) = split('/', $pParams['module_rsrc']);
    if ($package == '_custom:custom') {
        global $gBitLanguage;
        // We're gonna run our own cache mechanism for user_modules
        // the cache is here to avoid calls to consumming queries,
        // each module is different for each language because of the strings
        $cacheDir = TEMP_PKG_PATH . 'modules/cache/';
        if (!is_dir($cacheDir)) {
            mkdir_p($cacheDir);
        }
        $cachefile = $cacheDir . '_custom.' . $gBitLanguage->mLanguage . '.' . $template . '.tpl.cache';
        if (!empty($pParams["cache_time"]) && file_exists($cachefile) && !($gBitSystem->getUTCTime() - filemtime($cachefile) > $pParams["cache_time"])) {
            $fp = fopen($cachefile, "r");
            $data = fread($fp, filesize($cachefile));
            fclose($fp);
            print $data;
        } else {
            if ($moduleParams = $gBitThemes->getCustomModule($template)) {
                $moduleParams = array_merge($pParams, $moduleParams);
                $gBitSmarty->assign_by_ref('moduleParams', $moduleParams);
                $data = $gBitSmarty->fetch('bitpackage:themes/custom_module.tpl');
                if (!empty($pParams["cache_time"])) {
                    // write to chache file
                    $fp = fopen($cachefile, "w+");
                    fwrite($fp, $data, strlen($data));
                    fclose($fp);
                }
                print $data;
            }
        }
        unset($data);
    }
}
Ejemplo n.º 14
0
 public static function compile($__source__, $__target__)
 {
     $R = new self();
     require $__source__;
     $compilation = $R->perform_compile();
     $fp = fopen(__FILE__, 'r');
     fseek($fp, __COMPILER_HALT_OFFSET__);
     $compiled_source = '';
     $in = false;
     while (!feof($fp)) {
         $line = fgets($fp, 8192);
         if (preg_match('|// START-ROUTES|', $line)) {
             $compiled_source .= $compilation->export();
             $in = true;
         } elseif (preg_match('|// END-ROUTES|', $line)) {
             $in = false;
         } elseif (!$in) {
             $compiled_source .= $line;
         }
     }
     fclose($fp);
     mkdir_p(dirname($__target__));
     file_put_contents($__target__, ltrim($compiled_source));
 }
Ejemplo n.º 15
0
 function _run($file_id)
 {
     $this->system->__session_close(false);
     $this->cur_file_id = $file_id;
     $result = explode("|", $this->taskinfo['download_list'][$file_id]);
     $file_url = $result[0];
     if ($this->taskinfo['key_as_name']) {
         $file = $this->workdir . '/' . $file_id;
     } else {
         $file = $this->workdir . '/' . basename($file_url);
     }
     if (!is_dir($dir = dirname($file))) {
         mkdir_p($dir);
     }
     touch($file);
     $this->file_rs = fopen($file, 'rb+') or exit(__('Error: 无法创建文件:') . $file);
     fseek($this->file_rs, 0, SEEK_END);
     $cur_size = ftell($this->file_rs);
     $header = $cur_size ? array('Range' => 'bytes=' . $cur_size . '-') : null;
     set_time_limit($this->max_runtime + 3);
     $this->starttime = time();
     register_shutdown_function(array(&$this, '_next_request'));
     ob_start();
     $this->_next_request();
     $netcore =& $this->system->loadModel('utility/http_client');
     $netcore->get($file_url, $header, array(&$this, '_runner_handle'));
     ob_end_clean();
     while (key($this->taskinfo['download_list']) != $file_id) {
         next($this->taskinfo['download_list']);
     }
     if (next($this->taskinfo['download_list'])) {
         $this->cur_file_id = key($this->taskinfo['download_list']);
     } else {
         $this->cur_file_id = -1;
     }
 }
Ejemplo n.º 16
0
/**
 * mkdir -p replacement.
 * php<5 does not hav a mkdir -p function (create dirs recursively)
 * so use this implementation from  saint at corenova.com
 * found at www.php.net/mkdir
 */
function mkdir_p($target)
{
    if (is_dir($target) || empty($target)) {
        return 1;
        // best case check first
    }
    if (file_exists($target) && !is_dir($target)) {
        return 0;
    }
    if (mkdir_p(substr($target, 0, strrpos($target, '/')))) {
        return mkdir($target);
        // crawl back up & create dir tree
    }
    return 0;
}
Ejemplo n.º 17
0
	function mw_newMediaObject($args) {
	  // adapted from a patch by Johann Richard
	  // http://mycvs.org/archives/2004/06/30/file-upload-to-wordpress-in-ecto/

		global $wpdb;

	  $blog_ID     = $wpdb->escape($args[0]);
	  $user_login  = $wpdb->escape($args[1]);
		$user_pass   = $wpdb->escape($args[2]);
	  $data        = $args[3];

	  $name = $data['name'];
	  $type = $data['type'];
	  $bits = $data['bits'];

	  $file_realpath = get_settings('fileupload_realpath'); 
	  $file_url = get_settings('fileupload_url');

	  logIO('O', '(MW) Received '.strlen($bits).' bytes');

	  if (!$this->login_pass_ok($user_login, $user_pass)) {
	    return $this->error;
	  }

	  $user_data = get_userdatabylogin($user_login);

	  if(!get_settings('use_fileupload')) {
	    // Uploads not allowed
	    logIO('O', '(MW) Uploads not allowed');
	    $this->error = new IXR_Error(405, 'No uploads allowed for this site.');
	    return $this->error;
	  } 

	  if(get_settings('fileupload_minlevel') > $user_data->user_level) {
	    // User has not enough privileges
	    logIO('O', '(MW) Not enough privilege: user level too low');
	    $this->error = new IXR_Error(401, 'You are not allowed to upload files to this site.');
	    return $this->error;
	  }

	  if(trim($file_realpath) == '' || trim($file_url) == '' ) {
	    // WordPress is not correctly configured
	    logIO('O', '(MW) Bad configuration. Real/URL path not defined');
	    $this->error = new IXR_Error(500, 'Please configure WordPress with valid paths for file upload.');
	    return $this->error;
	  }

	  $prefix = '/';

	  if(!empty($name)) {
	    // Create the path
	    $localpath = $file_realpath.$prefix.$name;
	    $url = $file_url.$prefix.$name;

	    if (mkdir_p(dirname($localpath))) {

	      /* encode & write data (binary) */
	      $ifp = fopen($localpath, 'wb');
	      $success = fwrite($ifp, $bits);
	      fclose($ifp);
	      @chmod($localpath, 0666);

	      if($success) {
	        $resp = array('url' => $url);
	        return $resp;
	      } else {
	        logIO('O', '(MW) Could not write file '.$name.' to '.$localpath);
	        return new IXR_Error(500, 'Could not write file '.$name);
	      }

	    } else {
	      return new IXR_Error(500, 'Could not create directories for '.$name);
	    }
	  }
	}
Ejemplo n.º 18
0
 /**
  * Function responsible to copy a template.
  *
  * @access public
  * @return void
  */
 public function templatecopy()
 {
     if (!Permission::model()->hasGlobalPermission('templates', 'create')) {
         die('No permission');
     }
     $clang = $this->getController()->lang;
     $newname = sanitize_dirname(Yii::app()->request->getPost("newname"));
     $copydir = sanitize_dirname(Yii::app()->request->getPost("copydir"));
     $action = Yii::app()->request->getPost("action");
     if ($newname && $copydir) {
         // Copies all the files from one template directory to a new one
         Yii::app()->loadHelper('admin/template');
         $newdirname = Yii::app()->getConfig('usertemplaterootdir') . "/" . $newname;
         $copydirname = getTemplatePath($copydir);
         $oFileHelper = new CFileHelper();
         $mkdirresult = mkdir_p($newdirname);
         if ($mkdirresult == 1) {
             $oFileHelper->copyDirectory($copydirname, $newdirname);
             $templatename = $newname;
             $this->getController()->redirect(array("admin/templates/sa/view", 'templatename' => $newname));
         } elseif ($mkdirresult == 2) {
             Yii::app()->setFlashMessage(sprintf($clang->gT("Directory with the name `%s` already exists - choose another name"), $newname), 'error');
             $this->getController()->redirect(array("admin/templates/sa/view", 'templatename' => $copydir));
         } else {
             Yii::app()->setFlashMessage(sprintf($clang->gT("Unable to create directory `%s`."), $newname), 'error');
             Yii::app()->setFlashMessage($clang->gT("Please check the directory permissions."));
             $this->getController()->redirect(array("admin/templates/sa/view"));
         }
     } else {
         $this->getController()->redirect(array("admin/templates/sa/view"));
     }
 }
Ejemplo n.º 19
0
/**
* This function imports a LimeSurvey .lss survey XML file
*
* @param mixed $sFullFilePath  The full filepath of the uploaded file
*/
function XMLImportSurvey($sFullFilePath, $sXMLdata = NULL, $sNewSurveyName = NULL, $iDesiredSurveyId = NULL, $bTranslateInsertansTags = true, $bConvertInvalidQuestionCodes = true)
{
    Yii::app()->loadHelper('database');
    $clang = Yii::app()->lang;
    $aGIDReplacements = array();
    if ($sXMLdata == NULL) {
        $sXMLdata = file_get_contents($sFullFilePath);
    }
    $xml = @simplexml_load_string($sXMLdata, 'SimpleXMLElement', LIBXML_NONET);
    if (!$xml || $xml->LimeSurveyDocType != 'Survey') {
        $results['error'] = $clang->gT("This is not a valid LimeSurvey survey structure XML file.");
        return $results;
    }
    $pre_personal_characteristics = "";
    $question_groups['R'] = array();
    $question_groups['I'] = array();
    $question_groups['O'] = array();
    $iDBVersion = (int) $xml->DBVersion;
    $aQIDReplacements = array();
    $aQuestionCodeReplacements = array();
    $aQuotaReplacements = array();
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotals'] = 0;
    $results['quotamembers'] = 0;
    $results['survey_url_parameters'] = 0;
    $results['importwarnings'] = array();
    $aLanguagesSupported = array();
    foreach ($xml->languages->language as $language) {
        $aLanguagesSupported[] = (string) $language;
    }
    $results['languages'] = count($aLanguagesSupported);
    // Import surveys table ====================================================
    foreach ($xml->surveys->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $iOldSID = $results['oldsid'] = $insertdata['sid'];
        if ($iDesiredSurveyId != NULL) {
            $insertdata['wishSID'] = GetNewSurveyID($iDesiredSurveyId);
        } else {
            $insertdata['wishSID'] = $iOldSID;
        }
        if ($iDBVersion < 145) {
            if (isset($insertdata['private'])) {
                $insertdata['anonymized'] = $insertdata['private'];
            }
            unset($insertdata['private']);
            unset($insertdata['notification']);
        }
        //Make sure it is not set active
        $insertdata['active'] = 'N';
        //Set current user to be the owner
        $insertdata['owner_id'] = Yii::app()->session['loginID'];
        if (isset($insertdata['bouncetime']) && $insertdata['bouncetime'] == '') {
            $insertdata['bouncetime'] = NULL;
        }
        if (isset($insertdata['showXquestions'])) {
            $insertdata['showxquestions'] = $insertdata['showXquestions'];
            unset($insertdata['showXquestions']);
        }
        // Special code to set javascript in
        Yii::app()->loadHelper('admin/template');
        $newname = "watson_" . time();
        $newdirname = Yii::app()->getConfig('usertemplaterootdir') . "/" . $newname;
        $copydirname = getTemplatePath("watson_personal_constructs_copy_me");
        $oFileHelper = new CFileHelper();
        $mkdirresult = mkdir_p($newdirname);
        if ($mkdirresult == 1) {
            $oFileHelper->copyDirectory($copydirname, $newdirname);
            $templatename = $newname;
            //$this->index("startpage.pstpl", "welcome", $templatename);
        } elseif ($mkdirresult == 2) {
            $results['Error'] = sprintf($clang->gT("Directory with the name `%s` already exists - choose another name", "js"), $newname);
        } else {
            $results['Error'] = sprintf($clang->gT("Unable to create directory `%s`.", "js"), $newname) . " " . $clang->gT("Please check the directory permissions.", "js");
        }
        $insertdata['template'] = $newname;
        // End special copy code (taken from templates.php templatecopy() method
        if (isset($insertdata['googleAnalyticsStyle'])) {
            $insertdata['googleanalyticsstyle'] = $insertdata['googleAnalyticsStyle'];
            unset($insertdata['googleAnalyticsStyle']);
        }
        if (isset($insertdata['googleAnalyticsAPIKey'])) {
            $insertdata['googleanalyticsapikey'] = $insertdata['googleAnalyticsAPIKey'];
            unset($insertdata['googleAnalyticsAPIKey']);
        }
        if (isset($insertdata['allowjumps'])) {
            $insertdata['questionindex'] = $insertdata['allowjumps'] == "Y" ? 1 : 0;
            unset($insertdata['allowjumps']);
        }
        /* Remove unknow column */
        $aSurveyModelsColumns = Survey::model()->attributes;
        $aSurveyModelsColumns['wishSID'] = null;
        // To force a sid surely
        $aBadData = array_diff_key($insertdata, $aSurveyModelsColumns);
        $insertdata = array_intersect_key($insertdata, $aSurveyModelsColumns);
        // Fill a optionnal array of error
        foreach ($aBadData as $key => $value) {
            $results['importwarnings'][] = sprintf($clang->gT("This survey setting has not been imported: %s => %s"), $key, $value);
        }
        $iNewSID = $results['newsid'] = Survey::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [1]<br />");
        $pre_personal_characteristics = file_get_contents($newdirname . "/question.pstpl");
        $results['surveys']++;
    }
    // Import survey languagesettings table ===================================================================================
    foreach ($xml->surveys_languagesettings->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        if (!in_array($insertdata['surveyls_language'], $aLanguagesSupported)) {
            continue;
        }
        // Assign new survey ID
        $insertdata['surveyls_survey_id'] = $iNewSID;
        // Assign new survey name (if a copy)
        if ($sNewSurveyName != NULL) {
            $insertdata['surveyls_title'] = $sNewSurveyName;
        }
        if ($bTranslateInsertansTags) {
            $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_title']);
            if (isset($insertdata['surveyls_description'])) {
                $insertdata['surveyls_description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_description']);
            }
            if (isset($insertdata['surveyls_welcometext'])) {
                $insertdata['surveyls_welcometext'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_welcometext']);
            }
            if (isset($insertdata['surveyls_urldescription'])) {
                $insertdata['surveyls_urldescription'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_urldescription']);
            }
            if (isset($insertdata['surveyls_email_invite'])) {
                $insertdata['surveyls_email_invite'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_invite']);
            }
            if (isset($insertdata['surveyls_email_remind'])) {
                $insertdata['surveyls_email_remind'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_remind']);
            }
            if (isset($insertdata['surveyls_email_register'])) {
                $insertdata['surveyls_email_register'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_register']);
            }
            if (isset($insertdata['surveyls_email_confirm'])) {
                $insertdata['surveyls_email_confirm'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_confirm']);
            }
        }
        if (isset($insertdata['surveyls_attributecaptions']) && substr($insertdata['surveyls_attributecaptions'], 0, 1) != '{') {
            unset($insertdata['surveyls_attributecaptions']);
        }
        $result = SurveyLanguageSetting::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [2]<br />");
    }
    // Import groups table ===================================================================================
    if (isset($xml->groups->rows->row)) {
        foreach ($xml->groups->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported)) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $oldgid = $insertdata['gid'];
            unset($insertdata['gid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['group_name'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['group_name']);
                $insertdata['description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['description']);
            }
            // Insert the new group
            if (isset($aGIDReplacements[$oldgid])) {
                switchMSSQLIdentityInsert('groups', true);
                $insertdata['gid'] = $aGIDReplacements[$oldgid];
            }
            $newgid = QuestionGroup::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [3]<br />");
            if ($insertdata['group_name'] == 'Real Characteristics' || $insertdata['group_name'] == 'PC - Real Characteristics') {
                $question_groups['R'][] = $newgid;
            } else {
                if ($insertdata['group_name'] == 'Ideal Characteristics' || $insertdata['group_name'] == 'PC - Ideal Characteristics') {
                    $question_groups['I'][] = $newgid;
                } else {
                    if ($insertdata['group_name'] == 'Ought Characteristics' || $insertdata['group_name'] == 'PC - Ought Characteristics') {
                        $question_groups['O'][] = $newgid;
                    }
                }
            }
            $results['groups']++;
            if (!isset($aGIDReplacements[$oldgid])) {
                $aGIDReplacements[$oldgid] = $newgid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('groups', false);
            }
        }
    }
    // Import questions table ===================================================================================
    // We have to run the question table data two times - first to find all main questions
    // then for subquestions (because we need to determine the new qids for the main questions first)
    if (isset($xml->questions)) {
        foreach ($xml->questions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']];
            $oldqid = $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
            }
            // Insert the new question
            if (isset($aQIDReplacements[$oldqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            if (!$bConvertInvalidQuestionCodes) {
                $sScenario = 'archiveimport';
            } else {
                $sScenario = 'import';
            }
            $oQuestion = new Question($sScenario);
            $oQuestion->setAttributes($insertdata, false);
            // Try to fix question title for valid question code enforcement
            if (!$oQuestion->validate(array('title'))) {
                $sOldTitle = $oQuestion->title;
                $sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle);
                if (is_numeric(substr($sNewTitle, 0, 1))) {
                    $sNewTitle = 'q' . $sNewTitle;
                }
                $oQuestion->title = $sNewTitle;
            }
            $attempts = 0;
            // Try to fix question title for unique question code enforcement
            while (!$oQuestion->validate(array('title'))) {
                if (!isset($index)) {
                    $index = 0;
                    $rand = mt_rand(0, 1024);
                } else {
                    $index++;
                }
                $sNewTitle = 'r' . $rand . 'q' . $index;
                $oQuestion->title = $sNewTitle;
                $attempts++;
                if ($attempts > 10) {
                    safeDie($clang->gT("Error") . ": Failed to resolve question code problems after 10 attempts.<br />");
                }
            }
            if (!$oQuestion->save()) {
                // safeDie($clang->gT("Error while saving: "). print_r($oQuestion->errors, true));
                //
                // In PHP 5.2.10 a bug is triggered that resets the foreach loop when inserting a record
                // Problem is that it is the default PHP version on Ubuntu 12.04 LTS (which is currently very common in use)
                // For this reason we ignore insertion errors (because it is most likely a duplicate)
                // and continue with the next one
                continue;
            }
            // Set a warning if question title was updated
            if (isset($sNewTitle)) {
                $results['importwarnings'][] = sprintf($clang->gT("Question code %s was updated to %s."), $sOldTitle, $sNewTitle);
                $aQuestionCodeReplacements[$sOldTitle] = $sNewTitle;
                unset($sNewTitle);
                unset($sOldTitle);
            }
            $newqid = $oQuestion->qid;
            if (!isset($aQIDReplacements[$oldqid])) {
                $aQIDReplacements[$oldqid] = $newqid;
                $results['questions']++;
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
        }
    }
    // Import subquestions -------------------------------------------------------
    if (isset($xml->subquestions)) {
        foreach ($xml->subquestions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            if (!isset($insertdata['mandatory']) || trim($insertdata['mandatory']) == '') {
                $insertdata['mandatory'] = 'N';
            }
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
            $oldsqid = (int) $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                if (isset($insertdata['help'])) {
                    $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
                }
            }
            if (isset($aQIDReplacements[$oldsqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldsqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            if (!$bConvertInvalidQuestionCodes) {
                $sScenario = 'archiveimport';
            } else {
                $sScenario = 'import';
            }
            $question = new Question($sScenario);
            $question->setAttributes($insertdata, false);
            // Try to fix question title for valid question code enforcement
            if (!$question->validate(array('title'))) {
                $sOldTitle = $question->title;
                $sNewTitle = preg_replace("/[^A-Za-z0-9]/", '', $sOldTitle);
                if (is_numeric(substr($sNewTitle, 0, 1))) {
                    $sNewTitle = 'sq' . $sNewTitle;
                }
                $question->title = $sNewTitle;
            }
            $attempts = 0;
            // Try to fix question title for unique question code enforcement
            while (!$question->validate(array('title'))) {
                if (!isset($index)) {
                    $index = 0;
                    $rand = mt_rand(0, 1024);
                } else {
                    $index++;
                }
                $sNewTitle = 'r' . $rand . 'sq' . $index;
                $question->title = $sNewTitle;
                $attempts++;
                if ($attempts > 10) {
                    safeDie($clang->gT("Error") . ": Failed to resolve question code problems after 10 attempts.<br />");
                }
            }
            if (!$question->save()) {
                // safeDie($clang->gT("Error while saving: "). print_r($question->errors, true));
                //
                // In PHP 5.2.10 a bug is triggered that resets the foreach loop when inserting a record
                // Problem is that it is the default PHP version on Ubuntu 12.04 LTS (which is currently very common in use)
                // For this reason we ignore insertion errors (because it is most likely a duplicate)
                // and continue with the next one
                continue;
            }
            // Set a warning if question title was updated
            if (isset($sNewTitle)) {
                $results['importwarnings'][] = sprintf($clang->gT("Title of subquestion %s was updated to %s."), $sOldTitle, $sNewTitle);
                // Maybe add the question title ?
                $aQuestionCodeReplacements[$sOldTitle] = $sNewTitle;
                unset($sNewTitle);
                unset($sOldTitle);
            }
            $newsqid = $question->qid;
            if (!isset($insertdata['qid'])) {
                $aQIDReplacements[$oldsqid] = $newsqid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
            $results['subquestions']++;
        }
    }
    // Import answers ------------------------------------------------------------
    if (isset($xml->answers)) {
        foreach ($xml->answers->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || !isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['answer'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['answer']);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            if (Answer::model()->insertRecords($insertdata)) {
                $results['answers']++;
            }
        }
    }
    // Import questionattributes -------------------------------------------------
    if (isset($xml->question_attributes)) {
        $aAllAttributes = questionAttributes(true);
        foreach ($xml->question_attributes->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            // take care of renaming of date min/max adv. attributes fields
            if ($iDBVersion < 170) {
                if (isset($insertdata['attribute'])) {
                    if ($insertdata['attribute'] == 'dropdown_dates_year_max') {
                        $insertdata['attribute'] = 'date_max';
                    }
                    if ($insertdata['attribute'] == 'dropdown_dates_year_min') {
                        $insertdata['attribute'] = 'date_min';
                    }
                }
            }
            unset($insertdata['qaid']);
            if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if ($iDBVersion < 156 && isset($aAllAttributes[$insertdata['attribute']]['i18n']) && $aAllAttributes[$insertdata['attribute']]['i18n']) {
                foreach ($aLanguagesSupported as $sLanguage) {
                    $insertdata['language'] = $sLanguage;
                    if ($insertdata) {
                        XSSFilterArray($insertdata);
                    }
                    $result = QuestionAttribute::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[7]<br />");
                }
            } else {
                $result = QuestionAttribute::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[8]<br />");
            }
            $results['question_attributes']++;
        }
    }
    // Import defaultvalues ------------------------------------------------------
    if (isset($xml->defaultvalues)) {
        $results['defaultvalues'] = 0;
        foreach ($xml->defaultvalues->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if (isset($aQIDReplacements[(int) $insertdata['sqid']])) {
                $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']];
            }
            // remap the subquestion id
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            // now translate any links
            $result = DefaultValue::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[9]<br />");
            $results['defaultvalues']++;
        }
    }
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    // Import conditions ---------------------------------------------------------
    if (isset($xml->conditions)) {
        $results['conditions'] = 0;
        foreach ($xml->conditions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$insertdata['qid']])) {
                $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']];
                // remap the qid
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            if ($insertdata['cqid'] != 0) {
                if (isset($aQIDReplacements[$insertdata['cqid']])) {
                    $oldcqid = $insertdata['cqid'];
                    //Save for cfield transformation
                    $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']];
                    // remap the qid
                } else {
                    continue;
                }
                // a problem with this answer record -> don't consider
                list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $insertdata["cfieldname"], 3);
                // replace the gid for the new one in the cfieldname(if there is no new gid in the $aGIDReplacements array it means that this condition is orphan -> error, skip this record)
                if (!isset($aGIDReplacements[$oldcgid])) {
                    continue;
                }
            }
            unset($insertdata["cid"]);
            // recreate the cfieldname with the new IDs
            if ($insertdata['cqid'] != 0) {
                if (preg_match("/^\\+/", $oldcsid)) {
                    $newcfieldname = '+' . $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                } else {
                    $newcfieldname = $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                }
            } else {
                // The cfieldname is a not a previous question cfield but a {XXXX} replacement field
                $newcfieldname = $insertdata["cfieldname"];
            }
            $insertdata["cfieldname"] = $newcfieldname;
            if (trim($insertdata["method"]) == '') {
                $insertdata["method"] = '==';
            }
            // Now process the value and replace @sgqa@ codes
            if (preg_match("/^@(.*)@\$/", $insertdata["value"], $cfieldnameInCondValue)) {
                if (isset($aOldNewFieldmap[$cfieldnameInCondValue[1]])) {
                    $newvalue = '@' . $aOldNewFieldmap[$cfieldnameInCondValue[1]] . '@';
                    $insertdata["value"] = $newvalue;
                }
            }
            // now translate any links
            $result = Condition::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[10]<br />");
            $results['conditions']++;
        }
    }
    // TMSW Condition->Relevance:  Call  LEM->ConvertConditionsToRelevance
    // Import assessments --------------------------------------------------------
    if (isset($xml->assessments)) {
        foreach ($xml->assessments->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if ($insertdata['gid'] > 0) {
                $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
                // remap the qid
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            unset($insertdata['id']);
            // now translate any links
            $result = Assessment::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[11]<br />");
            $results['assessments']++;
        }
    }
    // Import quota --------------------------------------------------------------
    if (isset($xml->quota)) {
        foreach ($xml->quota->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $oldid = $insertdata['id'];
            unset($insertdata['id']);
            // now translate any links
            $result = Quota::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[12]<br />");
            $aQuotaReplacements[$oldid] = getLastInsertID('{{quota}}');
            $results['quota']++;
        }
    }
    // Import quota_members ------------------------------------------------------
    if (isset($xml->quota_members)) {
        foreach ($xml->quota_members->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']];
            // remap the qid
            unset($insertdata['id']);
            // now translate any links
            $result = QuotaMember::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[13]<br />");
            $results['quotamembers']++;
        }
    }
    // Import quota_languagesettings----------------------------------------------
    if (isset($xml->quota_languagesettings)) {
        foreach ($xml->quota_languagesettings->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']];
            // remap the qid
            unset($insertdata['quotals_id']);
            $result = QuotaLanguageSetting::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['quotals']++;
        }
    }
    // Import survey_url_parameters ----------------------------------------------
    if (isset($xml->survey_url_parameters)) {
        foreach ($xml->survey_url_parameters->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            if (isset($insertdata['targetsqid']) && $insertdata['targetsqid'] != '') {
                $insertdata['targetsqid'] = $aQIDReplacements[(int) $insertdata['targetsqid']];
                // remap the qid
            }
            if (isset($insertdata['targetqid']) && $insertdata['targetqid'] != '') {
                $insertdata['targetqid'] = $aQIDReplacements[(int) $insertdata['targetqid']];
                // remap the qid
            }
            unset($insertdata['id']);
            $result = SurveyURLParameter::model()->insertRecord($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data[14]<br />");
            $results['survey_url_parameters']++;
        }
    }
    // Set survey rights
    Permission::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSID);
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    $results['FieldReMap'] = $aOldNewFieldmap;
    LimeExpressionManager::SetSurveyId($iNewSID);
    translateInsertansTags($iNewSID, $iOldSID, $aOldNewFieldmap);
    replaceExpressionCodes($iNewSID, $aQuestionCodeReplacements);
    if (count($aQuestionCodeReplacements)) {
        array_unshift($results['importwarnings'], "<span class='warningtitle'>" . $clang->gT('Attention: Several question codes were updated. Please check these carefully as the update  may not be perfect with customized expressions.') . '</span)>');
    }
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
    LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
    $js_variables = array();
    if (!empty($question_groups['R'])) {
        $real_count = 1;
        $ideal_count = 1;
        $ought_count = 1;
        foreach ($results['FieldReMap'] as $code) {
            $value = explode('X', $code);
            if (isset($value[1]) && in_array($value[1], $question_groups['R'])) {
                if (!array_key_exists((int) $value[1], $js_variables)) {
                    $int = substr($value[2], 0, strpos($value[2], 'PC'));
                    $js_variables[$value[1]] = "var realGroupId" . $real_count . " = " . $value[1] . ";";
                    $js_variables[$value[1] . "-q"] = "var realQuestionId" . $real_count . " = " . $int . ";";
                    $real_count++;
                }
            } else {
                if (isset($value[1]) && in_array($value[1], $question_groups['I'])) {
                    if (!array_key_exists((int) $value[1], $js_variables)) {
                        $int = substr($value[2], 0, strpos($value[2], 'PC'));
                        $js_variables[$value[1]] = "var idealGroupId" . $ideal_count . " = " . $value[1] . ";";
                        $js_variables[$value[1] . "-q"] = "var idealQuestionId" . $ideal_count . " = " . $int . ";";
                        $ideal_count++;
                    }
                } else {
                    if (isset($value[1]) && in_array($value[1], $question_groups['O'])) {
                        if (!array_key_exists((int) $value[1], $js_variables)) {
                            $int = substr($value[2], 0, strpos($value[2], 'PC'));
                            $js_variables[$value[1]] = "var oughtGroupId" . $ought_count . " = " . $value[1] . ";";
                            $js_variables[$value[1] . "-q"] = "var oughtQuestionId" . $ought_count . " = " . $int . ";";
                            $ought_count++;
                        }
                    }
                }
            }
        }
        $js_variables[] = "var surveyId = " . $value[0] . ";";
    }
    if (!empty($js_variables)) {
        $pre_personal_characteristics = str_replace("[REPLACE_ME]", implode(PHP_EOL, $js_variables), $pre_personal_characteristics);
    } else {
        $pre_personal_characteristics = '<div {QUESTION_ESSENTIALS} class="{QUESTION_CLASS}{QUESTION_MAN_CLASS}{QUESTION_INPUT_ERROR_CLASS}">
          <div class="survey-question">
            <div class="survey-question-text">
                  <span class="asterisk">{QUESTION_MANDATORY}</span><span class="qnumcode"> {QUESTION_NUMBER} {QUESTION_CODE} </span>{QUESTION_TEXT}<br /><span class="questionhelp">{QUESTION_HELP}</span>
              {QUESTION_MAN_MESSAGE}
              {QUESTION_VALID_MESSAGE}
              {QUESTION_FILE_VALID_MESSAGE}
            </div>
            <div class="survey-question-answer">{ANSWER}</div>
            <div class="survey-question-help">{QUESTIONHELP}</div>
          </div>
          <div class="survey-question-space"></div>
        </div>';
    }
    file_put_contents($newdirname . "/question.pstpl", $pre_personal_characteristics);
    return $results;
}
Ejemplo n.º 20
0
define('ENABLE_SSL_ADMIN', 'false');
define('DIR_WS_ADMIN', BITCOMMERCE_PKG_URL . 'admin/');
define('DIR_WS_HTTPS_ADMIN', BITCOMMERCE_PKG_URL . 'admin/');
define('DIR_WS_CATALOG_TEMPLATE', HTTP_CATALOG_SERVER . DIR_WS_CATALOG . 'includes/templates/');
define('DIR_WS_CATALOG_LANGUAGES', HTTP_CATALOG_SERVER . DIR_WS_CATALOG . 'includes/languages/');
define('DIR_FS_ADMIN', '/a1/viovio/live/commerce/admin/');
define('DIR_FS_CATALOG_LANGUAGES', DIR_FS_CATALOG . 'includes/languages/');
define('DIR_FS_CATALOG_MODULES', DIR_FS_CATALOG . 'includes/modules/');
define('DIR_FS_CATALOG_TEMPLATES', DIR_FS_CATALOG . 'includes/templates/');
define('DIR_FS_CATALOG_BLOCKS', DIR_FS_CATALOG . 'includes/blocks/');
define('DIR_FS_CATALOG_BOXES', DIR_FS_CATALOG . 'includes/boxes/');
define('DIR_FS_BACKUP', DIR_FS_ADMIN . 'backups/');
define('DIR_FS_FILE_MANAGER_ROOT', BITCOMMERCE_PKG_PATH);
// path to starting directory of the file manager
define('DIR_FS_ADMIN_INCLUDES', 'includes/');
mkdir_p(DIR_FS_CATALOG_IMAGES);
/*

// Define the webserver and path parameters
  // Main webserver: eg, http://localhost - should not be empty for productive servers
  define('HTTP_SERVER', 'http://www.dev.viovio.com');
  // Secure webserver: eg, https://localhost - should not be empty for productive servers
  define('HTTPS_SERVER', 'https://www.dev.viovio.com'); // eg, https://localhost
  define('HTTP_CATALOG_SERVER', 'http://www.dev.viovio.com');
  define('HTTPS_CATALOG_SERVER', 'https://www.dev.viovio.com');

  // secure webserver for catalog module and/or admin areas?
  define('ENABLE_SSL_CATALOG', 'false');
  define('ENABLE_SSL_ADMIN', 'false');

// NOTE: be sure to leave the trailing '/' at the end of these lines if you make changes!
Ejemplo n.º 21
0
function board_parse_msg_parts(&$pPartHash, $pMbox, $pMsgId, $pMsgPart, $pPartNum, $pLog)
{
    //fetch part
    $part = imap_fetchbody($pMbox, $pMsgId, $pPartNum);
    switch ($pMsgPart->encoding) {
        case '3':
            // BASE64
            $part = base64_decode($part);
            break;
        case '4':
            // QUOTED-PRINTABLE
            $part = quoted_printable_decode($part);
            break;
            //0	7BIT
            //1	8BIT
            //2	BINARY
            //4	QUOTED-PRINTABLE
            //5	OTHER
    }
    if ($pLog) {
        print "Msg part " . $pPartNum . " type: " . $pMsgPart->subtype . "\n";
    }
    switch ($pMsgPart->type) {
        case '0':
            // make sure text is UTF-8
            if ($pMsgPart->ifparameters) {
                foreach ($pMsgPart->parameters as $params) {
                    // we trust the email source to specify the correct charset
                    // Note: alternatively one might run a check to make sure the text is really utf-8, regardless of the header
                    // use strtolower on the attributes since different php installs do not reconcile casing consistantly
                    if (strtolower($params->attribute) == 'charset' && strtolower($params->value) != 'utf-8') {
                        if ($pLog) {
                            print "Msg part " . $pPartNum . " charset: " . $params->value . "\n";
                        }
                        $part = @iconv($params->value, 'UTF-8', $part);
                    }
                }
            }
            // put msg in hash
            $pPartHash[$pPartNum][strtolower($pMsgPart->subtype)] = $part;
            break;
        default:
            // type is not text
            if (!preg_match('/signature/i', $pMsgPart->subtype)) {
                //get filename of attachment if present
                $filename = '';
                foreach (array('dparameters', 'parameters') as $prm) {
                    if (empty($filename)) {
                        // if there are any dparameters present in this part
                        if (!empty($pMsgPart->{$prm}) && count($pMsgPart->{$prm}) > 0) {
                            foreach ($pMsgPart->{$prm} as $param) {
                                if (strtoupper($param->attribute) == 'NAME' || strtoupper($param->attribute) == 'FILENAME') {
                                    $filename = $param->value;
                                }
                            }
                        }
                    }
                }
                //write to disk and set pPartHash variable
                if (!empty($filename)) {
                    //where to write file attachments to
                    srand(time());
                    $filestore = TEMP_PKG_PATH . BOARDS_PKG_NAME . '/boardsync/' . rand(999, 999999999) . '/' . $filename;
                    mkdir_p(dirname($filestore));
                    $pPartHash[$pPartNum]['attachment'] = $filestore;
                    $fp = fopen($filestore, "w+");
                    fwrite($fp, $part);
                    fclose($fp);
                }
            }
            break;
    }
    //if subparts... recurse into function and parse them too!
    if (!empty($pMsgPart->parts)) {
        foreach ($pMsgPart->parts as $pno => $parr) {
            board_parse_msg_parts($pPartHash, $pMbox, $pMsgId, $parr, $pPartNum . '.' . ($pno + 1), $pLog);
        }
    }
}
Ejemplo n.º 22
0
<?php

/**
 * @version $Header$
 * @package rss
 * @subpackage functions
 */
/**
 * Initialization
 */
require_once RSS_PKG_PATH . "feedcreator.class.php";
// make sure the feeds cache dir is available
if (!is_dir(TEMP_PKG_PATH . 'rss')) {
    mkdir_p(TEMP_PKG_PATH . 'rss');
}
// if http auth is required run it before we start anything else
if ($gBitSystem->getConfig('rssfeed_httpauth') && !empty($_REQUEST['httpauth']) && !$gBitUser->isRegistered()) {
    users_httpauth();
}
// initiate feed creator class
$rss = new UniversalFeedCreator();
$rss->copyright = $gBitSystem->getConfig('rssfeed_copyright');
$rss->editor = $gBitSystem->getConfig('rssfeed_editor');
$rss->webmaster = $gBitSystem->getConfig('rssfeed_webmaster');
$rss->language = $gBitSystem->getConfig('rssfeed_language', 'en-us');
$rss->cssStyleSheet = $gBitSystem->getConfig('rssfeed_css_url');
$rss->descriptionTruncSize = $gBitSystem->getConfig('rssfeed_truncate', 500);
$rss->descriptionHtmlSyndicated = TRUE;
$root = empty($_REQUEST['uri_mode']) ? BIT_BASE_URI . BIT_ROOT_URL : BIT_ROOT_URI;
$rss->link = $root;
$rss->syndicationURL = trim($root, "/") . $_SERVER['SCRIPT_NAME'];
Ejemplo n.º 23
0
 function instal_ol_app($file_path, $dir_name, &$msg, $update = false)
 {
     $app_path = PLUGIN_DIR . '/app/';
     if (!$update && is_dir($app_path . $dir_name)) {
         $msg = __('您已经安装过此应用,请返回已安装应用列表,点击应用后面的开启按钮即可使用。');
         return false;
     }
     $tar = $this->system->loadModel('utility/tar');
     if ($tar->openTAR($file_path)) {
         foreach ($tar->files as $id => $file) {
             $fpath = $app_path . $file['name'];
             if (!is_dir(dirname($fpath))) {
                 if (mkdir_p(dirname($fpath))) {
                     file_put_contents($fpath, $tar->getContents($file));
                 } else {
                     $msg = __('权限不允许');
                     return false;
                 }
             } else {
                 file_put_contents($fpath, $tar->getContents($file));
             }
         }
         $addon = $this->system->loadModel('system/addons');
         $addon->refresh();
     }
     return true;
 }
Ejemplo n.º 24
0
 function liberty_mime_get_storage_branch($pParamHash)
 {
     // $pSubDir = NULL, $pUserId = NULL, $pPackage = $gBitSystem->getActivePackage(), $pPermissions = 0755, $pCreateDir = true ) {
     // *PRIVATE FUNCTION. GO AWAY! DO NOT CALL DIRECTLY!!!
     global $gBitSystem;
     $pathParts = array();
     if ($pAttachmentId = BitBase::getParameter($pParamHash, 'attachment_id')) {
         $pathParts[] = 'attachments';
         $pathParts[] = (int) ($pAttachmentId % 1000);
         $pathParts[] = $pAttachmentId;
         // Added in fisheye override
     } else {
         $pathParts[] = 'common';
     }
     if ($pPackage = BitBase::getParameter($pParamHash, 'package')) {
         $pathParts[] = $pPackage;
     }
     $fullPath = implode($pathParts, '/') . '/';
     if (BitBase::getParameter($pParamHash, 'create_dir', TRUE)) {
         if (!file_exists(STORAGE_PKG_PATH . $fullPath)) {
             mkdir_p(STORAGE_PKG_PATH . $fullPath);
         }
     }
     return $fullPath;
 }
Ejemplo n.º 25
0
            //抓取间隔5s
        }
    }
}
//var_dump($r);
//save
$timestamp = strtotime('last day');
$filename = date('Ym', $timestamp) . '.txt';
$today = getdate($timestamp);
if ($r && is_array($r) && count($r) > 0) {
    foreach ($r as $engine => $val) {
        foreach ($val as $site => $urls) {
            foreach ($urls as $url => $num) {
                $dir = $C->DATA_DIR . 'record/' . $engine . '/' . $site . '/' . md5($url) . '/';
                if (!file_exists($dir)) {
                    mkdir_p($dir);
                }
                //判断是否已经记录过
                if (file_exists($dir . $filename)) {
                    $res = file($dir . $filename);
                    if (count($res) > 0) {
                        $last = explode('#####', array_pop($res));
                        if ($last[0] == $today['mday']) {
                            continue;
                        }
                    }
                }
                $content = $today['mday'] . '#####' . intval(str_replace(',', '', $num)) . "\n";
                //记录到文本
                $fp = fopen($dir . $filename, "a");
                if ($fp) {
Ejemplo n.º 26
0
 function do_install()
 {
     $sqlContent = file_get_contents('dbscripts/mysql.sql');
     $sqlContent .= file_get_contents('dbscripts/init.sql');
     if ($_POST['use_demo']) {
         $sqlContent .= file_get_contents('dbscripts/demo.sql');
     }
     $this->db->exec('SET NAMES utf8');
     foreach ($this->db->splitSql($sqlContent) as $sql) {
         if (!$this->db->exec($sql, true)) {
             $this->service_install_res('false', '<h3>Sql Error</h3><textarea style="width:500px;height:300px">' . htmlspecialchars($sql) . '</textarea><br />');
             //echo '<h3>Sql Error</h3><textarea style="width:500px;height:300px">'.htmlspecialchars($sql).'</textarea><br />';
             echo $this->db->errorInfo();
             exit;
         }
     }
     if ($this->install_mode == 'service') {
         $password = $_POST['password'];
     } else {
         $password = md5($_POST['password']);
     }
     if ($this->install_mode == 'usual') {
         $uname = $_POST['uname'] ? $_POST['uname'] : 'admin';
     } else {
         $uname = 'admin';
     }
     $rs = $this->db->exec('select * from sdb_operators where 0=1');
     $sql = $this->db->getInsertSQL($rs, array('username' => $uname, 'userpass' => $password, 'status' => 1, 'super' => 1));
     if (!$this->db->exec($sql, true)) {
         $this->service_install_res('false', 'error: cannot create administrator account.');
         exit;
     }
     if (RANDOM_HOME) {
         if (!is_dir(HOME_DIR)) {
             if (!mkdir(HOME_DIR, 0777)) {
                 $this->service_install_res('false', 'error: can\' mk home dir');
                 exit;
             }
         }
         if (!mkdir_p(HOME_DIR . '/cache/data') || !mkdir_p(HOME_DIR . '/cache/front_tmpl') || !mkdir_p(HOME_DIR . '/cache/admin_tmpl') || !mkdir_p(HOME_DIR . '/download') || !mkdir_p(HOME_DIR . '/fonts') || !mkdir_p(HOME_DIR . '/logs') || !mkdir_p(HOME_DIR . '/template') || !mkdir_p(HOME_DIR . '/upload')) {
             $this->service_install_res('false', 'error: can\' mk home dir');
             exit;
         }
     }
     $this->setConf('system.timezone.default', $_POST['timezone']);
     $this->init();
     $this->pagedata['password'] = $_POST['password'];
     $this->pagedata['uname'] = $uname;
     file_put_contents(BASE_DIR . 'config/install.lock', 'If you want to reinstall system, delete this file!');
     $this->cache->clear();
     $data['article'] = $this->db->selectrow("SELECT max(article_id) as max FROM sdb_articles");
     $data['goods'] = $this->db->selectrow("SELECT max(goods_id) as max FROM sdb_goods");
     $data['goods_cat'] = $this->db->selectrow("SELECT max(cat_id) as max FROM sdb_goods_cat");
     $data['goods_memo'] = $this->db->selectrow("SELECT max(goods_id) as max FROM sdb_goods_memo");
     $data['goods_type'] = $this->db->selectrow("SELECT max(type_id) as max FROM sdb_goods_type");
     $data['package_product'] = $this->db->selectrow("SELECT max(product_id) as max FROM sdb_package_product");
     $data['products'] = $this->db->selectrow("SELECT max(product_id) as max FROM sdb_products");
     $data['spec_values'] = $this->db->selectrow("SELECT max(spec_value_id) as max FROM sdb_spec_values");
     $data['specification'] = $this->db->selectrow("SELECT max(spec_id) as max FROM sdb_specification");
     $data['type_brand'] = $this->db->selectrow("SELECT max(type_id) as max FROM sdb_type_brand");
     $data['brand'] = $this->db->selectrow("SELECT max(brand_id) as max FROM sdb_brand");
     $data['goods_virtual_cat'] = $this->db->selectrow("SELECT max(virtual_cat_id) as max FROM sdb_goods_virtual_cat");
     $data['gimages'] = $this->db->selectrow("SELECT max(gimage_id) as max FROM sdb_gimages");
     $data['status'] = $this->db->selectrow("SELECT max(last_update) as max FROM sdb_status");
     $this->setConf('system.test.database', serialize($data));
 }
Ejemplo n.º 27
0
/**
 * liberty_process_generic
 *
 * @param array $pFileHash
 * @param array $pMoveFile
 * @access public
 * @return TRUE on success, FALSE on failure - mErrors will contain reason for failure
 */
function liberty_process_generic(&$pFileHash, $pMoveFile = TRUE)
{
    global $gBitSystem;
    $ret = NULL;
    if (!empty($pFileHash['dest_file'])) {
        $destFile = $pFileHash['dest_file'];
    } else {
        if ($gBitSystem->isFeatureActive('liberty_originalize_file_names')) {
            $destFile = STORAGE_PKG_PATH . $pFileHash['dest_branch'] . liberty_mime_get_default_file_name($pFileHash['name'], $pFileHash['type']);
        } else {
            $destFile = STORAGE_PKG_PATH . $pFileHash['dest_branch'] . $pFileHash['name'];
        }
        if (is_windows()) {
            $destFile = str_replace('//', '\\', str_replace("\\", '\\', $destFile));
        }
    }
    mkdir_p(dirname($destFile));
    if (is_file($pFileHash['source_file'])) {
        if ($pFileHash['source_file'] == $destFile) {
            // do nothing if source and dest are the same
        } elseif ($pMoveFile) {
            if (is_uploaded_file($pFileHash['source_file'])) {
                move_uploaded_file($pFileHash['source_file'], $destFile);
            } else {
                rename($pFileHash['source_file'], $destFile);
            }
        } else {
            copy($pFileHash['source_file'], $destFile);
        }
        $ret = $destFile;
    }
    $pFileHash['size'] = filesize($destFile);
    return $ret;
}
Ejemplo n.º 28
0
 function backupPackage($dstpkg, $dir = "backup")
 {
     $work = XOOPS_UPLOAD_PATH . "/update/work/{$dir}";
     $pname = $this->getVar('pname');
     $pat = $this->regIgnore();
     foreach ($this->checkUpdates($dstpkg) as $path => $method) {
         if ($pat && preg_match($pat, $path)) {
             continue;
         }
         $file = "{$work}/" . $this->getRealPath($path, false);
         if ($method == 'skip') {
             continue;
         }
         if (!mkdir_p(dirname($file))) {
             die("can't mkdir with {$file}");
         }
         $src = $this->getRealPath($path);
         if (file_exists($src) && !link($src, $file)) {
             if (!copy($src, $file)) {
                 echo "<div>copy failed: {$pname} - {$src} to {$file}<div>\n";
             }
         }
     }
     return true;
 }
Ejemplo n.º 29
0
function temp_dir($default = false)
{
    global $ptmp, $prefix;
    if ($default) {
        if (!@is_dir($default)) {
            if (!mkdir_p($default)) {
                return false;
            }
        }
        /* try it really, is_writable is buggy with openbasedir */
        $fh = @fopen(realpath($default) . "/test", "wb");
        if ($fh) {
            $ptmp = $default;
            return true;
        } else {
            $ptmp = "failed";
            return false;
        }
    }
    $_temp = false;
    if (WINDOWS) {
        if (my_env('TEMP')) {
            $_temp = my_env('TEMP');
        } elseif (my_env('TMP')) {
            $_temp = my_env('TMP');
        } elseif (my_env('windir')) {
            $_temp = my_env('windir') . '\\temp';
        } elseif (my_env('SystemRoot')) {
            $_temp = my_env('SystemRoot') . '\\temp';
        }
        // handle ugly ENV var like \Temp instead of c:\Temp
        $dirs = explode("\\", realpath($_temp));
        if (strpos($_temp, ":") != 1) {
            unset($_temp);
            $_dirs = array();
            foreach ($dirs as $val) {
                if ((bool) $val) {
                    $_dirs[] = str_replace("/", "", $val);
                }
            }
            unset($dirs);
            $dirs = $_dirs;
            array_unshift($dirs, "c:");
            $_temp = $dirs[0];
            for ($i = 1; $i < count($dirs); $i++) {
                $_temp .= "//" . $dirs[$i];
            }
        }
        $ptmp = $_temp;
    } else {
        $_temp = my_env('TMPDIR');
        if (!$_temp) {
            if (is_writable('/tmp')) {
                $_temp = '/tmp';
            }
        }
    }
    // If for some reason the user has no rights to access to
    // the standard tempdir, we assume that he has the right
    // to access his prefix and choose $prefix/tmp as tempdir
    if (!$_temp) {
        print "System's Tempdir failed, trying to use \$prefix/tmp ...";
        $res = mkdir_p($prefix . '/tmp');
        if (!$res) {
            bail('mkdir ' . $prefix . '/tmp' . ' ... failed');
        }
        $ptmp = $prefix . '/tmp';
        $_temp = tempnam($prefix . '/tmp', 'gope');
        rm_rf($_temp);
        mkdir_p($_temp, 0700);
        $ok = @chdir($ptmp);
        if (!$ok) {
            // This should not happen, really ;)
            bail('chdir ' . $ptmp . ' ... failed');
        }
        print "ok\n";
        // Adjust TEMPDIR envvars
        if (!isset($_ENV)) {
            $_ENV = array();
        }
        $_ENV['TMPDIR'] = $_ENV['TEMP'] = $prefix . '/tmp';
    } else {
        $_temp = tempnam($_temp . '/tmp', 'gope');
    }
    $temp_dir = $ptmp = $_temp;
    return true;
}
Ejemplo n.º 30
0
 function recover($sTgz, $vols, $fileid)
 {
     $prefix = substr($sTgz, 0, 23);
     $sTmpDir = HOME_DIR . '/tmp/' . md5($sTgz) . '/';
     if ($fileid == 1) {
         $rTar = $this->system->loadModel('utility/tar');
         mkdir_p($sTmpDir);
         if ($rTar->openTAR(HOME_DIR . '/backup/' . $sTgz)) {
             foreach ($rTar->files as $id => $aFile) {
                 if (substr($aFile['name'], -4) == '.sql') {
                     $sPath = $sTmpDir . $aFile['name'];
                     file_put_contents($sPath, $rTar->getContents($aFile));
                 }
             }
         }
         $rTar->closeTAR();
         $this->comeback($sTmpDir . $prefix . '_1.sql');
     } else {
         $this->comeback($sTmpDir . $prefix . '_' . $fileid . '.sql');
     }
     if ($vols == $fileid) {
         //do updatescripts
         $info = $this->getInfo(HOME_DIR . '/backup/' . $sTgz);
         $pkgRev = $info['backup']['rev'];
         $ver = $this->system->version();
         $appRev = $ver['rev'];
         $sDir = realpath(CORE_DIR . '/updatescripts');
         if ($pkgRev < $appRev) {
             $upgrade =& $this->system->loadModel('system/upgrade');
             echo '<pre>';
             $scripts = $upgrade->scripts($pkgRev, $appRev);
             foreach ($scripts as $sqlFile) {
                 if (false !== ($sql = file_get_contents(CORE_DIR . '/updatescripts/' . $sqlFile[0]))) {
                     foreach ($this->db->splitSql($sql) as $line) {
                         $this->db->exec($line);
                     }
                 }
             }
             $this->db->exec("drop table if exists sdb_dbver");
             $this->db->exec("create table sdb_dbver(`{$appRev}` varchar(255)) type = MYISAM");
         }
         $this->__finish($sTmpDir);
     }
 }