TeraWurflAdmin
[ class tree: TeraWurflAdmin ] [ index: TeraWurflAdmin ] [ all elements ]

Source for file cmd_line_admin.php

Documentation is available at cmd_line_admin.php

  1. <?php
  2. /**
  3.  * Tera_WURFL - PHP MySQL driven WURFL
  4.  * 
  5.  * Tera-WURFL was written by Steve Kamerman, and is based on the
  6.  * Java WURFL Evolution package by Luca Passani and WURFL PHP Tools by Andrea Trassati.
  7.  * This version uses a MySQL database to store the entire WURFL file, multiple patch
  8.  * files, and a persistent caching mechanism to provide extreme performance increases.
  9.  * 
  10.  * @package TeraWurflAdmin
  11.  * @author Steve Kamerman <stevekamerman AT gmail.com>
  12.  * @version Stable 2.1.3 $Date: 2010/09/18 15:43:21
  13.  * @license http://www.mozilla.org/MPL/ MPL Vesion 1.1
  14.  */
  15. /**
  16.  * Include required files
  17.  */
  18. require_once realpath(dirname(__FILE__).'/../TeraWurfl.php');
  19. require_once realpath(dirname(__FILE__).'/../TeraWurflLoader.php');
  20. require_once realpath(dirname(__FILE__).'/../TeraWurflXMLParsers/TeraWurflXMLParser.php');
  21. require_once realpath(dirname(__FILE__).'/../TeraWurflXMLParsers/TeraWurflXMLParser_XMLReader.php');
  22. require_once realpath(dirname(__FILE__).'/../TeraWurflXMLParsers/TeraWurflXMLParser_SimpleXML.php');
  23.  
  24. if(TeraWurflConfig::$OVERRIDE_MEMORY_LIMITini_set("memory_limit",TeraWurflConfig::$MEMORY_LIMIT);
  25.  
  26. $args parseArgs($_SERVER['argv']);
  27.  
  28. $base new TeraWurfl();
  29. if($base->db->connected !== true){
  30.     throw new Exception("Cannot connect to database: ".$base->db->errors[0]);
  31. }
  32. $twversion $base->release_branch " " $base->release_version;
  33. $wurflversion $base->db->getSetting('wurfl_version');
  34. $lastupdated date('r',$base->db->getSetting('loaded_date'));
  35.  
  36. //var_export($args);
  37. if(empty($args|| array_key_exists('help',$args)){
  38.     $usage =<<<EOL
  39.  
  40. Tera-WURFL $twversion
  41. The command line WURFL updater for Tera-WURFL
  42. Loaded WURFL: $wurflversion
  43. Last Updated: $lastupdated
  44. ---------------------------------------
  45. Usage: php cmd_line_admin.php [OPTIONS]
  46.  
  47. Option                     Meaning
  48.  --help                    Show this message
  49.  --update=<local,remote>   The source of the WURFL file:
  50.                              Update from your local wurfl.xml file:
  51.                                --update=local
  52.                              Update from wurfl.sourceforge.net:
  53.                                --update=remote
  54.  --clearCache              Clear the device cache
  55.  --rebuildCache            Rebuild the device cache by redetecting all
  56.                              cached devices using the current WURFL
  57.  --stats                   Show statistics about the Tera-WURFL Database
  58.  
  59.  
  60. EOL;
  61.     echo $usage;
  62.     exit(0);
  63. }
  64.  
  65. // Parse arguments
  66. $action null;
  67. if(array_key_exists('update',$args)){
  68.     $source = (string)$args['update'];
  69.     if($source != "local" && $source != "remote"){
  70.         echo "You must specify a source when using the --update option.  Use --help for help\n\n";
  71.         exit(1);
  72.     }
  73.     $action "update";
  74. }
  75. if(array_key_exists('clearCache',$args)){
  76.     $base->db->createCacheTable();
  77.     echo "Device cache has been cleared.\n";
  78. }
  79. if(array_key_exists('rebuildCache',$args)){
  80.     if($action != "update"){
  81.         $base->db->rebuildCacheTable();
  82.         echo "Device cache has been rebuilt.\n";
  83.     }
  84. }
  85. if(array_key_exists('stats',$args)){
  86.     $config $base->rootdir."TeraWurflConfig.php";
  87.     $dbtype str_replace("TeraWurflDatabase_","",get_class($base->db));
  88.     $dbver $base->db->getServerVersion();
  89.     $mergestats $base->db->getTableStats(TeraWurflConfig::$TABLE_PREFIX.'Merge');
  90.     $mergestats['bytesize'WurflSupport::formatBytes($mergestats['bytesize']);
  91.     $merge "\n > MERGE
  92.    Rows:    {$mergestats['rows']}
  93.    Devices: {$mergestats['actual_devices']}
  94.    Size:    {$mergestats['bytesize']}\n";
  95.     $index "";
  96.     $indexstats $base->db->getTableStats(TeraWurflConfig::$TABLE_PREFIX.'Index');
  97.     if(!empty($indexstats)){
  98.         $indexstats['bytesize'WurflSupport::formatBytes($indexstats['bytesize']);
  99.         $index "\n > INDEX
  100.    Rows:    {$indexstats['rows']}
  101.    Size:    {$indexstats['bytesize']}\n";
  102.     }
  103.     $cachestats $base->db->getTableStats(TeraWurflConfig::$TABLE_PREFIX.'Cache');
  104.     $cachestats['bytesize'WurflSupport::formatBytes($cachestats['bytesize']);
  105.     $cache "\n > CACHE
  106.    Rows:    {$cachestats['rows']}
  107.    Size:    {$cachestats['bytesize']}\n";
  108.     $matcherList $base->db->getMatcherTableList();
  109.     $matchers array();
  110.     foreach($matcherList as $name){
  111.         $matchers[array('name'=>$name,'stats'=>$base->db->getTableStats($name));
  112.     }
  113.     $out =<<<EOF
  114. Tera-WURFL $twversion
  115. Database Type: $dbtype (ver $dbver)
  116. Loaded WURFL: $wurflversion
  117. Last Updated: $lastupdated
  118. Config File: $config
  119. ---------- Table Stats -----------
  120. {$merge}{$index}{$cache}
  121. EOF;
  122.     echo $out;
  123.     exit(0);
  124. }
  125. if(array_key_exists('debug',$args)){
  126.     switch($args['debug']){
  127.         case "constIDgrouped":
  128.             $matcherList UserAgentFactory::$matchers;
  129.             foreach($matcherList as $matcher){
  130.                 $matcherClass $matcher."UserAgentMatcher";
  131.                 $file $base->rootdir."UserAgentMatchers/{$matcherClass}.php";
  132.                 require_once($file);
  133.                 $ids $matcherClass::$constantIDs;
  134.                 if(empty($ids)) continue;
  135.                 echo "\n$matcherClass\n\t".implode("\n\t",$ids);
  136.             }
  137.             break;
  138.         case "constIDunique":
  139.             $matcherList UserAgentFactory::$matchers;
  140.             $ids array();
  141.             foreach($matcherList as $matcher){
  142.                 $matcherClass $matcher."UserAgentMatcher";
  143.                 $file $base->rootdir."UserAgentMatchers/{$matcherClass}.php";
  144.                 require_once($file);
  145.                 $ids array_merge($ids,$matcherClass::$constantIDs);
  146.             }
  147.             $ids array_unique($ids);
  148.             sort($ids);
  149.             echo implode("\n",$ids);
  150.             break;
  151.         case "createProcs":
  152.             echo "Recreating Procedures.\n";
  153.             $base->db->createProcedures();
  154.             echo "Done.\n";
  155.             break;
  156.         case "batchLookupFallback":
  157.             $raw file_get_contents($args['file']);
  158.             $ids preg_split('/[\n\r]+/',$raw);
  159.             unset($raw);
  160.             foreach($ids as $id){
  161.                 $fallback array();
  162.                 if($base->db->db_implements_fallback){
  163.                     $tree $base->db->getDeviceFallBackTree($id);
  164.                     foreach($tree as $node$fallback[]=$node['id'];
  165.                 }else{
  166.                     die("Unsupported on this platform\n");
  167.                 }
  168.                 echo implode(', ',$fallback)."\n";
  169.             }
  170.             break;
  171.     }
  172. }
  173. if(is_null($action)){
  174.     echo "\n";
  175.     exit(0);
  176. }
  177.  
  178. $newfile TeraWurfl::absoluteDataDir().TeraWurflConfig::$WURFL_FILE.".zip";
  179. $wurflfile TeraWurfl::absoluteDataDir().TeraWurflConfig::$WURFL_FILE;
  180.  
  181. if($source == "remote" || $source == "remote_cvs"){
  182.     if($source == "remote"){
  183.         $dl_url TeraWurflConfig::$WURFL_DL_URL
  184.     }elseif($source == "remote_cvs"){
  185.         $dl_url TeraWurflConfig::$WURFL_CVS_URL;
  186.     }
  187.     echo "Downloading WURFL from $dl_url ...\n\n";
  188.     flush();
  189.     if(!file_exists($newfile&& !is_writable($base->rootdir.TeraWurflConfig::$DATADIR)){
  190.         $base->toLog("Cannot write to data directory (permission denied)",LOG_ERR);
  191.         Throw New Exception("Fatal Error: Cannot write to data directory (permission denied). (".$base->rootdir.TeraWurflConfig::$DATADIR.")\n\nPlease make the data directory writable by the user or group that runs the webserver process, in Linux this command would do the trick if you're not too concerned about security: chmod -R 777 ".$base->rootdir.TeraWurflConfig::$DATADIR);
  192.         exit(1);
  193.     }
  194.     if(file_exists($newfile&& !is_writable($newfile)){
  195.         $base->toLog("Cannot overwrite WURFL file (permission denied)",LOG_ERR);
  196.         Throw New Exception("Fatal Error: Cannot overwrite WURFL file (permission denied). (".$base->rootdir.TeraWurflConfig::$DATADIR.")\n\nPlease make the data directory writable by the user or group that runs the webserver process, in Linux this command would do the trick if you're not too concerned about security: chmod -R 777 ".$base->rootdir.TeraWurflConfig::$DATADIR);
  197.         exit(1);
  198.     }
  199.     // Download the new WURFL file and save it in the DATADIR as wurfl.zip
  200.     @ini_set('user_agent'"PHP/Tera-WURFL_$version");
  201.     $download_start microtime(true);
  202.     if(!$gzdata file_get_contents($dl_url)){
  203.         Throw New Exception("Error: Unable to download WURFL file from ".TeraWurflConfig::$WURFL_DL_URL);
  204.         exit(1);
  205.     }
  206. /*    $destination=fopen($newfile,"w"); 
  207.     $source=fopen($dl_url,"r"); 
  208.     while ($block=fread($source,256*1024)) fwrite($destination,$block);
  209.     fclose($source);
  210.     fclose($destination);
  211. */
  212.     $download_time microtime(true$download_start;
  213.     file_put_contents($newfile,$gzdata);
  214.     $gzsize WurflSupport::formatBytes(filesize($newfile));
  215.     // Try to use ZipArchive, included from 5.2.0
  216.     if(class_exists("ZipArchive")){
  217.         $zip new ZipArchive();
  218.         if ($zip->open(str_replace('\\','/',$newfile)) === TRUE{
  219.             $zip->extractTo(str_replace('\\','/',dirname($wurflfile)),array('wurfl.xml'));
  220.             $zip->close();
  221.         else {
  222.             Throw New Exception("Error: Unable to extract wurfl.xml from downloaded archive: $newfile");
  223.             exit(1);
  224.         }
  225.     }else{
  226.         system("gunzip $newfile");
  227.     }
  228.     $size WurflSupport::formatBytes(filesize($wurflfile))." [$gzsize compressed]";
  229.     $download_rate WurflSupport::formatBitrate(filesize($newfile)$download_time);
  230.     $ok true;
  231.     echo "done ($wurflfile$size)\nDownloaded in $download_time sec @ $download_rate \n\n";
  232.     usleep(50000);
  233.     flush();
  234. }
  235.  
  236. $loader new TeraWurflLoader($base);
  237. //$ok = $base->db->initializeDB();
  238. $ok $loader->load();
  239. if($ok){
  240.     echo "Database Update OK\n";
  241.     echo "Total Time: ".$loader->totalLoadTime()."\n";
  242.     echo "Parse Time: ".$loader->parseTime()." (".$loader->getParserName().")\n";
  243.     echo "Validate Time: ".$loader->validateTime()."\n";
  244.     echo "Sort Time: ".$loader->sortTime()."\n";
  245.     echo "Patch Time: ".$loader->patchTime()."\n";
  246.     echo "Database Time: ".$loader->databaseTime()."\n";
  247.     echo "Cache Rebuild Time: ".$loader->cacheRebuildTime()."\n";
  248.     echo "Number of Queries: ".$base->db->numQueries."\n";
  249.     if(version_compare(PHP_VERSION,'5.2.0'=== 1){
  250.         echo "PHP Memory Usage: ".WurflSupport::formatBytes(memory_get_usage())."\n";
  251.     }
  252.     echo "--------------------------------\n";
  253.     echo "WURFL Version: ".$loader->version." (".$loader->last_updated.")\n";
  254.     echo "WURFL Devices: ".$loader->mainDevices."\n";
  255.     echo "PATCH New Devices: ".$loader->patchAddedDevices."\n";
  256.     echo "PATCH Merged Devices: ".$loader->patchMergedDevices."\n";
  257. }else{
  258.     echo "ERROR LOADING DATA!\n";
  259.     echo "Errors: \n\n";
  260.     echo htmlspecialchars(var_export($loader->errors,true));
  261. }
  262.  
  263. /**
  264.  * Command Line Interface (CLI) options parser
  265.  * @author pwfisher
  266.  * @see http://pwfisher.com/nucleus/index.php?itemid=45
  267.  * @param array Raw command line arguments
  268.  */
  269. function parseArgs($argv){
  270.     array_shift($argv)$o array();
  271.     foreach ($argv as $a){
  272.         if (substr($a,0,2== '--')$eq strpos($a,'=');
  273.             if ($eq !== false)$o[substr($a,2,$eq-2)substr($a,$eq+1)}
  274.             else $k substr($a,2)if (!isset($o[$k]))$o[$ktrue} } }
  275.         else if (substr($a,0,1== '-'){
  276.             if (substr($a,2,1== '=')$o[substr($a,1,1)substr($a,3)}
  277.             else foreach (str_split(substr($a,1)) as $k)if (!isset($o[$k]))$o[$ktrue} } } }
  278.         else $o[$a} }
  279.     return $o;
  280. }

Documentation generated on Sun, 19 Sep 2010 00:15:49 +0000 by phpDocumentor 1.4.3