Back to Top

Category: Misc Topics

Splitting a video using linux command line

Best way I have found to split a mp4 video on linux is to use

avconv -ss {start time in seconds} -i {source mp4} -t {duration in seconds}  -vcodec copy -acodec copy -metadata track="{track number}" "{output mp4}" 

where
{start time in seconds} is the time from the beginning of the video in seconds to set the start marker of clip eg 0 for the video beginning

{duration in seconds} is the duration from the marker start to set the end marker of clip eg 200 for 200 seconds from the beginning of the video

{source mp4} is the path to the source mp4 video eg source.mp4

{track number} is the integer current track number eg 1,2,3 etc

{output mp4} is the path to the output mp4 split video eg part-1.mp4

Easy to adapt for a shell script or as I use a php wrapper script.

Can use ffmpeg instead but I don’t find the video quality very good.

 

 

Posted in Misc Topics |

Getting phantomjs working on CentOS servers

If anyone else gets the following error on trying to use the 64 bit version of phantomjs binary..

./phantomjs: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory
yum install zlib.i686

Try using yum to install the following packages..

yum -y install glibc.i686
yum install zlib.i686
yum install fontconfig freetype freetype-devel fontconfig-devel libstdc++
yum install libfontconfig.so.1
yum install libstdc++.so.6

Worked for myself.

Posted in Misc Topics |

Linking Dailymotion rss feed to twitter

The purpose of this post is to show how to link a dailymotion video rss feed to your twitter account using Codebird php, so when the script runs it adds one video post to your twitter account.. can then be run via a cron setup (won’t cover here as system dependent – windows v linux servers).

You need three things sorted out first..

(1) Down the codebird for php library from https://github.com/jublonet/codebird-php

(2) Obtain a twitter developer api key details from https://apps.twitter.com/app/new (best to log into your twitter account first)

(3) Have a Dailymotion rss feed – usually of format http://www.dailymotion.com/rss/user/[daily motion user name] – where [daily motion user name] is your user account name of account.

The code looks like the following.. things to replace are in [] brackets.

Note: I have taken out my code for shortening links and auto hash tagging using str_ireplace(), but the principles here should get you in the right direction.


require_once("codebird.php"); // reference the codebird php library file (downloaded in step one above)

class BlogPost
{
    var $date;
    var $ts;
    var $link;
    var $title;
    var $text;
}

class BlogFeed
{
    var $posts = array();

    function __construct($file_or_url)
    {
        $file_or_url = $this->resolveFile($file_or_url);
        if (!($x = simplexml_load_file($file_or_url)))  {
           return;
        }

        foreach ($x->channel->item as $item)
        {

            $post = new BlogPost();
            $post->date  = (string) $item->pubDate;
            $post->ts    = strtotime($item->pubDate);
            $post->link  = (string) $item->link;
            $post->title = (string) $item->title;

            $post->text = ""; // not using this for tweets

            $this->posts[] = $post;
        }
    }

    private function resolveFile($file_or_url) {
        if (!preg_match('|^https?:|', $file_or_url))
            $feed_uri = $file_or_url;
        else
            $feed_uri = $file_or_url;

        return $feed_uri;
    }

    private function summarizeText($summary) {
        $summary = strip_tags($summary);

        // Truncate summary line to 100 characters
        $max_len = 100;
        if (strlen($summary) > $max_len)
            $summary = substr($summary, 0, $max_len) . '...';

        return $summary;
    }
}


// read in posts

$ps = new BlogFeed("http://www.dailymotion.com/rss/user/[daily motion user name]"); // your dailymotion rss feed (step three above)

$posts = $ps->posts;

$c=count($posts);
$r=rand(1,$c);
$r=$r-1;
$p=$posts[$r];
$link=$p->link;
$title=$p->title;
if($link!="") {


$message = $title." ".$link; // note that the twitter 140 character limit applies to the total of message sent

// now tweet - [] key information unique to twitter account - obtain keys via https://apps.twitter.com/app/new (step two above)

\Codebird\Codebird::setConsumerKey('[YOURKEY]', '[YOURSECRET]');
$cb = \Codebird\Codebird::getInstance();
$cb->setToken("[YOURTOKEN]", "[YOURTOKENSECRET]");

$params = array(
    'status' => $message
);

$reply = $cb->statuses_update($params);

// display message to screen

echo($message);

}

?>

Note: disclaimers on code/snippet usage applies – no responsibility on usage.

Posted in Misc Topics |

Top Three Simple Things I Would Like To Be Sorted Out On OneDrive Online

This relates to office365 onedrive for business

A list of three I believe to be simple things I would like, really like, to be sorted out on onedrive online so I can actually use it without ripping my hair out on a day to day basis.. pretty please…

1) ‘Keep me signed in’ tick box actually worked on firefox browsers – no cleaning software or cookie removal plugins, just doesn’t work on firefox fullstop. Tried a fresh profile, still doesn’t work, forced to play enter the email/password game each time.

2) Developers stopped or reduced making subtle changes to the login form url and/or field names – ok storing your email address and password in browser wallets isn’t ideal, but given (1) above, it becomes tiresome when the url or field names change, so then your email and password isn’t automatically filled in, so then have to play hunt the password game to login each time – kind of important if shares are sent to me with login forced on them.. (note I do have a firefox plugin which allows SSL / https passwords to be auto filed, but like all sites only works if the login form urls are kept consistent… unlike right now).

3) Once logged into a onedrive shared FOLDER, if I move from ‘FILES’ to ‘OUR FILES’, then switch back to ‘FILES’ again all the shared files disappear – only solution is to log out, then (hoping url hasn’t been altered rofl in the meantime) re-enter email/password details, and log back in, just remembering not to switch to ‘OUR FILES’ by mistake – this tends to happen if the same client has sent more than one share eg input folder as one share and an output folder as another share – annoying as hell anyway.

Many other issues on Onedrive online, but if these 3 issues above were fixed, could possibly regain my hair cover and lower overall stress levels.

Additional: The protected mode ‘file is corrupted’ message when two different people using excel 2016 share the same document but slightly different versions of the software used ought to be changed though – cannot keep expecting clients to change their security settings just because say my version of excel 2016 is 2 weeks more up to date than theirs or vice-a-versa.. tested and found to be the case. Probably less of a case on forced updating windows 10, but as those people who might rely on expensive mobile broadband turn off auto updates (5GB == £40, which can soon mount up on office 2016 updates), is definitely an issue in my opinion.

Posted in Misc Topics |

WordPress Virtual Pages

This wordpress function class code can be used to create virtual on the fly pages – note they won’t show up by default on widgets or in menues (they only exist when physically called via slug url), but can be custom linked. Possible to create links to them using header / footer filters/hooks. Also ideal if you want dynamic content displayed.

Replace the following with page urls (slug), title and contents..

‘slug’ => ”,
‘post_title’ => ”,
‘post_content’ => ”

if (!class_exists('wp_virtual_page_setup')){
    class wp_virtual_page_setup
    {

        public $slug ='';
        public $args = array();

        function __construct($args){
            $this->args = $args;
            $this->slug = $args['slug'];
            add_filter('the_posts',array($this,'virtual_page'));
        }

        public function virtual_page($posts){
            global $wp,$wp_query;
            $page_slug = $this->slug;

            if(count($posts) == 0 && (strtolower($wp->request) == $page_slug || $wp->query_vars['page_id'] == $page_slug)){

                //virtual page
                $post = new stdClass;
                $post->post_author = 1;
                $post->post_name = $page_slug;
                $post->guid = get_bloginfo('wpurl' . '/' . $page_slug);
                $post->post_title = 'page title';
                //put your custom content here
                $post->post_content = "Fake Content";
                //just needs to be a number - negatives are fine
                $post->ID = -42;
                $post->post_status = 'static';
                $post->comment_status = 'closed';
                $post->ping_status = 'closed';
                $post->comment_count = 0;
                $post->post_date = current_time('mysql');
                $post->post_date_gmt = current_time('mysql',1);
                $post = (object) array_merge((array) $post, (array) $this->args);
                $posts = NULL;
                $posts[] = $post;

                $wp_query->is_page = true;
                $wp_query->is_singular = true;
                $wp_query->is_home = false;
                $wp_query->is_archive = false;
                $wp_query->is_category = false;
                unset($wp_query->query["error"]);
                $wp_query->query_vars["error"]="";
                $wp_query->is_404 = false;
            }

            return $posts;
        }
    }//end class
}//end if

$args = array(
        'slug' => '',
        'post_title' => '',
        'post_content' => ''
);
new wp_virtual_page_setup($args);

Posted in Misc Topics |

Better PHP US Phone number validation function

I have replaced phone validation functions in contact scripts as seems to work better with a range of different US phone numbers..

function VALIDATE_USPHONE($phonenumber,$useareacode=true)
{
if ( preg_match("/^[ ]*[(]{0,1}[ ]*[0-9]{3,3}[ ]*[)]{0,1}[-]{0,1}[ ]*[0-9]{3,3}[ ]*[-]{0,1}[ ]*[0-9]{4,4}[ ]*$/",$phonenumber) || (preg_match("/^[ ]*[0-9]{3,3}[ ]*[-]{0,1}[ ]*[0-9]{4,4}[ ]*$/",$phonenumber) && !$useareacode)) return eregi_replace("[^0-9]", "", $phonenumber);
if ( preg_match("/^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})$/",$phonenumber) ) return eregi_replace("[^0-9]", "", $phonenumber);
if ( (strlen(eregi_replace("[^0-9]", "", $phonenumber))>=6)&&(strlen(eregi_replace("[^0-9]", "", $phonenumber))<=16) ) return eregi_replace("[^0-9]", "", $phonenumber);
return false;
}
Posted in Misc Topics |

Try this fix if you get a mysql error 2006 on importing database

Sometimes you just cannot get that mysql database file to import, even via the command line.

eg mysql -p -u username databasename < databasefile.sql and you get a nasty ERROR 2006 - MYSQL server has gone away message in return. The first obvious thought is that it is somekind of timeout issue, so you waste ages playing around with the interactive and wait timeout values. Try this instead, or in addition to the time out values.. Edit the /etc/my.cnf file and either add or edit the appropiate line in the [mysqld] block and make

max_allowed_packet=64M

Then restart mysql again:

service mysql restart

and try to import your database again – worked for me.

Posted in Misc Topics |

Add common styling parameter to string image tags

This I have found useful for dealling with class/styling removed from simplepie rss incoming feeds in wordpress.. in this example all tags have a padding:10px; style automatically added. Useful for wordpress content filters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
 
$string = "<br><p><img src='image1.jpg'></p><br><img src='image2.jpg'>";
 
 
echo add_img_style($string,'padding:10px;');
 
 
function add_img_style($string,$style) {
 
$xml = new DOMDocument();
 
@$xml->loadHTML($string);
 
    foreach($xml->getElementsByTagName('img') as $link)
    {
    $link->setAttribute('style', $style);
    }
 
$o= preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $xml->saveHTML()));
$o= str_ireplace("\n","",$o);
return $o;
 
}
 
?>
Posted in Misc Topics |

Code to email an attachment

PHP function code to add an attachment – data to be put into an attached file called $filename, is stored in variable $data ::

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
 
function attach_mail($to, $subject, $message, $header, $filename, $data){
$data = chunk_split(base64_encode($data));
$uid = md5(uniqid(time()));
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/html; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".basename($filename)."\"\r\n" .
"Content-Description: ".basename($filename)."\r\n" .
"Content-Disposition: attachment;\r\n" . " filename=\"".basename($filename)."\"; size=".strlen($data).";\r\n" .
"Content-Transfer-Encoding: base64\r\n\r\n" . $data . "\r\n\r\n";
$header .= "--".$uid."--";
$ok = @mail($to, $subject, "", $header);
if($ok){ return 1; } else { return 0; }
}
 
?>
Posted in Misc Topics |