Drupal 7: how to get the modules list - php

How to get the modules list in Drupal as in admin/build/modules?

You can use drush pm-list --type=Module --status=enabled command for getting a list of installed modules.

Install "Drush" (a good option in any case, once you get used to it, you'll love it). It has a build in command to list all installed modules themes.
If you need to see the list of modules to display it elsewhere (this can be a security issue!), you can look into the way how drush does it (pm.drush.inc:218).
Furthermore there is a core function, but I don't know if this is what you want.

module_list($refresh = FALSE, $bootstrap_refresh = FALSE, $sort = FALSE, $fixed_list = NULL)
Here are more details.
http://api.drupal.org/api/drupal/includes!module.inc/function/module_list/7

If you want to list all the modules available to you, this should work with either Drupal 6 or Drupal 7:
<?php
// include_once('.' . base_path() . drupal_get_path('module', 'system') . '/system.admin.inc');
// Above line was intentionally commented out (see below).
$drupal_version = (int) VERSION;
$list_modules_function = '';
if ($drupal_version >= 7 && $drupal_version < 8) {
$list_modules_function = 'system_rebuild_module_data';
}
else if ($drupal_version >= 6 && $drupal_version < 7) {
$list_modules_function = 'module_rebuild_cache';
}
if (empty($list_modules_function)) {
$output = t('Oops... Looks like you are not using either version 6 or version 7 of Drupal');
}
else if (!function_exists($list_modules_function)) {
$output = t('Oops... Unable to find the function !function(). Try uncommenting the top line of this code.', array('!function' => $list_modules_function));
}
else {
$output = "<dl>\n";
$list_modules = $list_modules_function();
foreach ($list_modules as $module) {
$output .= "<dt>" . check_plain($module->info["name"]) . "</dt>\n";
$output .= "<dd>" . check_plain($module->info["description"]) . "</dd>\n";
}
$output .= "</dl>\n";
}
print $output;
?>

You can also use following commands to search specific modules.
If you want to list-down only commerce module from module list than
drush pml | grep commerce
On windows machine you cant use grep. So you have to use findstr
drush pml | findstr commerce

The following command will work, outputing list of all available modules along with the package they fall in, status and version.
drush pm-list --type=Module --status=enabled

Related

Read Windows Installer (MSI file) attributes from PHP

I have a Windows MSI file, that I need to programmatically read the version number from. The only place I can see this version is within the Subject of the file details:
If I somehow can read the entire content of Subject this would be fine but is there any way to get this from PHP? The PHP is running in an IIS web server, if this helps ;-)
stat is of no help for this.
I considered doing a checksum of the file, and can do that, but I really need the real version.
For now I am unable to find a native PHP solution for this, so I have temporarily solved this by calling a Powershell script as it seems easier to do in there.
I am now having this PHP code:
$version = exec("powershell.exe -file GetMsiVersion.ps1 MyFile.msi);
With my above picture then $version will contain 1.5.9, so I will not even require to interpret the data from Subject.
The GetMsiVersion.ps1 Powershell script has this code:
function Get-Property ($Object, $PropertyName, [object[]]$ArgumentList) {
return $Object.GetType().InvokeMember($PropertyName, 'Public, Instance, GetProperty', $null, $Object, $ArgumentList)
}
function Invoke-Method ($Object, $MethodName, $ArgumentList) {
return $Object.GetType().InvokeMember($MethodName, 'Public, Instance, InvokeMethod', $null, $Object, $ArgumentList)
}
$Path = $args[0]
$msiOpenDatabaseModeReadOnly = 0
$Installer = New-Object -ComObject WindowsInstaller.Installer
$Database = Invoke-Method $Installer OpenDatabase #($Path, $msiOpenDatabaseModeReadOnly)
$View = Invoke-Method $Database OpenView #("SELECT Value FROM Property WHERE Property='ProductVersion'")
Invoke-Method $View Execute
$Record = Invoke-Method $View Fetch
if ($Record) {
Write-Output (Get-Property $Record StringData 1)
}
Invoke-Method $View Close #()
I will accept this as the best solution here-and-now but, I hope this can be archieved natively from PHP as I see this as a better and more clean solution - and by then I will accept that as the best answer (or at least unaccept my own temporary solution).
Doing an exec is a little evil ;-)
Two things first:
I have never accessed COM from PHP, but below are some VBScript samples of getting information from MSI files by using MSI API - COM automation. There are also Win32 functions.
That field you refer to is not a version field, but a text field from the MSI's "Summary Stream" - a special part of the MSI file with "meta information" of various kinds. Summary Information Stream (the full name).
Here is how you can get the REAL version of an MSI file. This is stored in the property "ProductVersion" in the MSI file. There are at least two different ways to retrieve it - by opening the MSI file as a session or just access the property table via SQL query:
Access version via Session object:
Const msiUILevelNone = 2
Dim installer : Set installer = CreateObject("WindowsInstaller.Installer")
installer.UILevel = msiUILevelNone
Set s = installer.OpenPackage("C:\MySetup.msi",1)
MsgBox CStr(s.ProductProperty("ProductVersion"))
Accessing version via SQL agains MSI database (property table):
Dim installer : Set installer = CreateObject("WindowsInstaller.Installer")
' Open MSI database in read-only mode (0)
Set db = installer.OpenDatabase("C:\MySetup.msi", 0)
Set view = db.OpenView("SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'")
view.Execute
Set record = view.Fetch
MsgBox CStr(record.StringData(1))
Then there is the issue of accessing the SummaryStream - which is what you are really asking by the looks of it - here is a simple smoke test with some hints as to what properties you can retrieve - be careful with the summary stream - corruption is possible in various ways (I don't recall the details, but it should be safe to access read-only):
Dim installer : Set installer = CreateObject("WindowsInstaller.Installer")
' Open MSI database in read-only mode (0)
Set db = installer.OpenDatabase("C:\MySetup.msi", 0)
MsgBox CStr(db.SummaryInformation.Property(3))
' 1 = "Codepage"
' 2 = "Title"
' 3 = "Subject"
' 4 = "Author"
' 5 = "Keywords"
' 6 = "Comments"
' 7 = "Template"
' 8 = "LastAuthor"
' 9 = "Revision"
' 11 = "Printed"
' 12 = "Created"
' 13 = "Saved"
' 14 = "Pages"
' 15 = "Words"
' 16 = "Characters"
' 18 = "Application"
' 19 = "Security"
Links:
Modify an MSI using MSI SQL VBScript WiRunSQL.vbs
List tables in MSI file using VBScript

GRAV git-sync plugin update crashing web-site, has anyone encountered/solved?

I've been using GRAV as a CMS for a small experimental site. I recently updated the git-sync plugin, and am suddenly stuck with a website that produces only errors, with no way to enter the admin gui (all web access to the site crashes with same errors), to downgrade the git-sync module, or for that matter, to upgrade the git-sync plugin if there is a fix.
I'm a developer that hasn't really thought much about web development in decades (my, how it's changed), so there are a few things I have to admit upfront. I don't know sht about php, and really don't care to if I don't have to.
The message I get (below) indicates that this is a php error. If this is a simple syntax fix please give me a heads up.
If you have any advice on a "cli" way to use the git-sync plugin to upgrade or downgrade, revert the git-sync, or any other hints, advise away. I'll dig in to more documentation and see if I end up answering my own question.
/[pathToUserHome]/grav/user/plugins/git-sync/classes/GitSync.php
*/
$paths = ['.'];
if (version_compare($version, '2.0', '<')) {
$add .= ' --all';
}
return $this->execute($add . ' ' . implode(' ', $paths));
}
public function commit($message = '(Grav GitSync) Automatic Commit')
{
$authorType = $this->getGitConfig('author', 'gituser');
if (defined('GRAV_CLI') && in_array($authorType, ['gravuser', 'gravfull'])) {
$authorType = 'gituser';
}
// get message from config, it any, or stick to the default one
$message = $this->getConfig('git', null)['message'] ?? $message;
// get Page Title and Route from Post
$pageTitle = $_POST['data']['header']['title']??'NO TITLE FOUND';
$pageRoute = $_POST['data']['route']??'NO ROUTE FOUND';
...
Arguments
1) "syntax error, unexpected '?'"
Whoops\Exception\ErrorException…
/user/plugins/git-sync/classes/GitSync.php : 223
$message = $this->getConfig('git', null)['message'] ?? $message;
Your new version of GRAV is using php7.0 features, like ?? operator, which is Null coalescing. Try to upgrade your php version to support new features, or downgrade GRAV.
Make a compatible version is also an option, but it could be time consumption idea. However, if your problems only in this particular file, you could replace:
// $message = $this->getConfig('git', null)['message'] ?? $message;
$message = isset($this->getConfig('git', null)['message']) ? $this->getConfig('git', null)['message'] : $message;
// $pageTitle = $_POST['data']['header']['title']??'NO TITLE FOUND';
$pageTitle = isset($_POST['data']['header']['title']) ? $_POST['data']['header']['title'] : 'NO TITLE FOUND';
// $pageRoute = $_POST['data']['route']??'NO ROUTE FOUND';
$pageRoute = isset($_POST['data']['route']) ? $_POST['data']['route'] : 'NO ROUTE FOUND';

Index data with Solr PHP Client

I'm using the Solr PHP Client and have the Solr 4.3.0 example up and running. I have not modified the schema.xml file. When I run this code I get a 400 error:
Uncaught exception 'Apache_Solr_HttpTransportException' with message '400' Status: Bad Request.'
The document does not show up in the index. Interestingly, If I restart Jetty, the document is indexed. Here's my code. I was wondering if I'm missing something. I thought this was an issue with my input matching the schema, but id seems to be the only required field and these other fields are in the schema. I'm not sure what to do.
require_once('SolrPhpClient/Apache/Solr/Service.php');
$solr = new Apache_Solr_Service('localhost', 8983, '/solr/');
if($solr->ping() == null){
die('could not ping solr');
}
$document = new Apache_Solr_Document();
$document->id = 'guid1';
$document->title = 'Title1';
$document->subject = 'The subject is solr';
$document->description = 'This is the description';
$solr->addDocument($document);
$solr->commit();
The full error message I get is
Fatal error: Uncaught exception 'Apache_Solr_HttpTransportException' with message ''400' Status: Bad Request' in C:\xampp\htdocs\dev\SolrPhpClient\Apache\Solr\Service.php:364
Stack trace:
#0 C:\xampp\htdocs\dev\SolrPhpClient\Apache\Solr\Service.php(829): Apache_Solr_Service->_sendRawPost('http://localhos...', '<commit expunge...', 3600)
#1 C:\xampp\htdocs\dev\indexerSOLR_PHP.php(20): Apache_Solr_Service->commit()
#2 {main} thrown in C:\xampp\htdocs\dev\SolrPhpClient\Apache\Solr\Service.php on line 364`
This is a known issue with Solr 4.x and calling commit from the Solr PHP Client. Please see
Bug #62332 - As of solr 4.0 the waitFlush parameter is removed for commit for the details and a patch to fix the issue.
That is what how I got the solution, I modified commit method. Added '&commit=true' to the _updateurl variable.
public function commit($expungeDeletes = false, $waitFlush = true, $waitSearcher = true, $timeout = 3600)
{
$expungeValue = $expungeDeletes ? 'true' : 'false';
$flushValue = $waitFlush ? 'true' : 'false';
$searcherValue = $waitSearcher ? 'true' : 'false';
//$rawPost = '<commit expungeDeletes="' . $expungeValue . '" waitFlush="' . $flushValue . '" waitSearcher="' . $searcherValue . '" />';
//$this->post=$rawPost;
return $this->_sendRawGet($this->_updateUrl.'&commit=true', $timeout);
}
You have change this line.
require_once('SolrPhpClient/Apache/Solr/Service.php'); => require_once('Service.php');
Maybe Service.php this file's path wrong. I try to changed this line. Then work successfully.
I had the same issue because I have installed an old version of the PHP Solr extension (0.9.11).
To get a the latest one:
pecl download solr-beta
tar xvzf solr-2.1.0.tgz # This can be different depending on the last release number
cd solr-2.1.0/
phpize
./configure
make
sudo make install
# add extension=solr.so to your php.ini / distribution extension loader
Thanks to this post.

Is there a PHP library for looking up vendor from MAC address?

I have a list of MAC addresses coming from a database. I would like to lookup the vendor for each MAC address and then have a count of devices on network by vendor in the end.
I believe I could do it the dirty way which would be to parse the vendor prefixes from the file available here http://standards.ieee.org/develop/regauth/oui/oui.txt.
But I'm wondering if there is a better way ?
There is a library in Pear, but it does have substantial overhead involved in that the vendor lookup requires a relational database that's been loaded with the vendor data. However, considering the alternative this might be worth exploring.
http://pear.php.net/manual/en/package.networking.net-mac.php
The package provides a loader for the list maintained by wireshark: https://code.wireshark.org/review/gitweb?p=wireshark.git;a=blob_plain;f=manuf
If all you care about is getting the manufacturer of the device based on the mac address then you can simply copy and paste the list on this website here (unto 200 at a time). It's very quick:
www.admin-toolkit.com/mac-address-lookup-manufacturer.html
But I'm wondering if there is a better way ?
If you can use other languages like ruby, there's a gem called macvendors
There is no need to use an external api or get stopped by rate limit.
You can use it from your command line:
gem install macvendors
macvendors find 98:e0:d9:a5:61:eb
Apple, Inc.
You can use it in your ruby code:
require 'macvendors'
MacVendors.setup #for the first time
puts MacVendors.find("98:e0:d9:a5:61:eb")
I have made an SQlite (Macvendors.db) from the Wireshark manuf source. I use it via PDO with a simple query.
Here is a method I write to show you how you could use it:
public function getAllCompaniesFromMacs($macs)
{
try {
// connect to the SQLite file
$conn = new \PDO("sqlite:/path/to/sqlite/Macvendors.db");
$conn ->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
// aux vars
$macsParaBuscar = array();
$macsIN = "";
// output vars
$salida = array();
// Clean repeated MACs and remove the ":" chars
foreach ($macs as $unaMac) {
$unaMac = str_replace(":", "", $unaMac);
$firstChars = substr($unaMac, 0, 6);
$macsParaBuscar[$firstChars] = $firstChars;
}
// Create a IN statment for the WHERE
$macsIN = "( 'HOLA'";
foreach ($macsParaBuscar as $unaMacBuscar) {
$macsIN .= ", '" . $unaMacBuscar . "'";
}
$macsIN .= ")";
// Prepare and execute the query
$stm = $conn->prepare("SELECT mac, vendor FROM macvendor WHERE mac IN " . $macsIN);
$stm->execute();
// Put results in output var
while( $row = $stm->fetch() ) {
$auxMac = $row["mac"];
$salida[$auxMac] = $row["vendor"];
}
return $salida;
} catch (\Exception $e) {
throw new \Exception("Ha ocurrido un error", 1);
}
}
Sorry about the unbeauty example code.
Have fun!
Update
There is another library that doesn't depend on any API but the XML file database which is Cisco vendorMacs.xml
The package is hosted here
Yes here is one I wrote, it depends on the online API of Mac address vendor website
Here is the repository with examples

Reading a Git commit message from PHP

I'm looking for a way to read a Git commit message with PHP. I suspect I need to use a Git hook, but I've never worked with them before, so I need a push in the right direction. Specifically, I'd like to implement the following process:
A PHP script is executed automatically after every commit
The script captures the Git username, the time of the commit, and the commit content
If at all possible, I'd like to stick with pure PHP. If there are tutorials or references that you could point out, that would be a huge help.
To get the commit hash, you can use
git rev-parse --verify HEAD 2> /dev/null
From within php:
exec('git rev-parse --verify HEAD 2> /dev/null', $output);
$hash = $output[0];
You can get the commit message, author and time (though - the time will simply be "now" if it's run as part of a post-commit hook) with:
exec("git show $hash", $output);
If it's not obvious, whatever you do with php is simply going to be a wrapper around the things you'd do with git on the cli - I.e. any "how can I do x with git from php" is just exec('the git answer', $output)
As far as using PHP to extract the correct commit:
Indefero
There is a project called Indefero that is a PHP forge tool that has an SCM connector for git. You could easily use their git class as an API for yourself. You can just grab the git class and the SCM class.
I have, for example, pulled out two methods from the class below, which I think are the most relevant to you so you can see how they work.
Get a changelog list: getChangeLog()
/**
* Get latest changes.
*
* #param string Commit ('HEAD').
* #param int Number of changes (10).
* #return array Changes.
*/
public function getChangeLog($commit='HEAD', $n=10)
{
if ($n === null) $n = '';
else $n = ' -'.$n;
$cmd = sprintf('GIT_DIR=%s '.Pluf::f('git_path', 'git').' log%s --date=iso --pretty=format:\'%s\' %s',
escapeshellarg($this->repo), $n, $this->mediumtree_fmt,
escapeshellarg($commit));
$out = array();
$cmd = Pluf::f('idf_exec_cmd_prefix', '').$cmd;
self::exec('IDF_Scm_Git::getChangeLog', $cmd, $out);
return self::parseLog($out);
}
Get a particular commit: getCommit()
/**
* Get commit details.
*
* #param string Commit
* #param bool Get commit diff (false)
* #return array Changes
*/
public function getCommit($commit, $getdiff=false)
{
if ($getdiff) {
$cmd = sprintf('GIT_DIR=%s '.Pluf::f('git_path', 'git').' show --date=iso --pretty=format:%s %s',
escapeshellarg($this->repo),
"'".$this->mediumtree_fmt."'",
escapeshellarg($commit));
} else {
$cmd = sprintf('GIT_DIR=%s '.Pluf::f('git_path', 'git').' log -1 --date=iso --pretty=format:%s %s',
escapeshellarg($this->repo),
"'".$this->mediumtree_fmt."'",
escapeshellarg($commit));
}
$out = array();
$cmd = Pluf::f('idf_exec_cmd_prefix', '').$cmd;
self::exec('IDF_Scm_Git::getCommit', $cmd, $out, $ret);
if ($ret != 0 or count($out) == 0) {
return false;
}
if ($getdiff) {
$log = array();
$change = array();
$inchange = false;
foreach ($out as $line) {
if (!$inchange and 0 === strpos($line, 'diff --git a')) {
$inchange = true;
}
if ($inchange) {
$change[] = $line;
} else {
$log[] = $line;
}
}
$out = self::parseLog($log);
$out[0]->diff = implode("\n", $change);
} else {
$out = self::parseLog($out);
$out[0]->diff = '';
}
$out[0]->branch = implode(', ', $this->inBranches($commit, null));
return $out[0];
}
VersionControl_Git from PEAR
There is also a library in PEAR called VersionControl_Git that would be helpful in this situation and is documented.
As #Pawel mentioned, you're going to want to work with hooks on this:
On localhost you can navigate to /.git/hooks and rename
post-commit.sample to post-commit and then put inside #!/usr/bin/php
There are also other hooks that may be more
suitable for you.
Git will look for the post-commit hook after you've commit and automatically run anything inside.
What you're going to want to do here depends on the task, but I'd suggest curling the script - here's where things get interesting.
In order to extract the information you're looking for, you're going to want to use git log -1 - that should pull back the latest commit.
More specifically, you'll want to build your commit using the --pretty=format toggle, which can output the latest commit with the info you need. Check out this string:
git log -1 --pretty=format:'%h - %cn (%ce) - %s (%ci)'
This would return most of the things you are looking for. Check out the git-log page to see all of the different % variables that you can use with --pretty=format:. Once you've made the string that you'd like, you can either POST those via cURL to a PHP script, or run a PHP script and use shell_exec(git log -1 --pretty=format:'%h - %cn (%ce) - %s (%ci)') to work with the commit message inline.
I was digging in the same question and found out a way to do it faster and easier.
To get just the commit message you could use
git rev-list --format=%B --max-count=1 HEAD
Obviously HEAD may be replaced with any commit hash.
It will output something like
commit 4152601a42270440ad52680ac7c66ba87a506174
Improved migrations and models relations
Second line is what you need.

Categories